Note that there are some explanatory texts on larger screens.

plurals
  1. POMy databinding with value converter does not work
    text
    copied!<p>I've got a simple Item-class, that looks like this:</p> <pre><code>public class Item : DependencyObject { public int No { get { return (int)GetValue(NoProperty); } set { SetValue(NoProperty, value); } } public string Name { get { return (string)GetValue(NameProperty); } set { SetValue(NameProperty, value); } } public static readonly DependencyProperty NoProperty = DependencyProperty.Register("No", typeof(int), typeof(Item)); public static readonly DependencyProperty NameProperty = DependencyProperty.Register("Name", typeof(string), typeof(Item)); } </code></pre> <p>And a ValueConverter, that looks like this:</p> <pre><code>[ValueConversion(typeof(Item), typeof(string))] internal class ItemToStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) { return null; } var item = ((Item)value); var sb = new StringBuilder(); sb.AppendFormat("Item # {0}", item.No); if (string.IsNullOrEmpty(item.Name) == false) { sb.AppendFormat(" - [{0}]", item.Name); } return sb.ToString(); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } </code></pre> <p>On my WPF Window, I declare a DependencyProperty (called Items) that holds a list of Item objects (List&lt; Item >) and creates a ComboBox that binds to this DependencyProperty using this XAML-code:</p> <pre><code>&lt;ComboBox ItemsSource="{Binding ElementName=mainWindow, Path=Items}"&gt; &lt;ComboBox.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;TextBlock Text="{Binding Converter={StaticResource itemToStringConverter}}"/&gt; &lt;/DataTemplate&gt; &lt;/ComboBox.ItemTemplate&gt; &lt;/ComboBox&gt; </code></pre> <p>If I execute the code below once, the databinding works fine, howevery the value convertion fails if I execute it again:</p> <pre><code>var item1 = new Item {Name = "Item A", No = 1}; var item2 = new Item {Name = "Item B", No = 2}; var item3 = new Item {Name = "Item C", No = 3}; Items = new List&lt;Item&gt; {item1, item2, item3}; </code></pre> <p>The problem is, that the ItemToStringConverter.Convert method is now passed a string-object as the first parameter instead of an Item-object?</p> <p>What am I doing wrong?</p> <p>Regards, Kenneth</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload