我有一个简单的 Item-class,看起来像这样:
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));
}
还有一个 ValueConverter,看起来像这样:
[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();
}
}
在我的 WPF 窗口中,我声明了一个 DependencyProperty(称为 Items),它包含一个 Item 对象列表(List< Item >),并使用此 XAML 代码创建一个绑定到此 DependencyProperty 的 ComboBox:
<ComboBox ItemsSource="{Binding ElementName=mainWindow, Path=Items}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource itemToStringConverter}}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
如果我执行一次下面的代码,数据绑定工作正常,但是如果我再次执行它,值转换会失败:
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<Item> {item1, item2, item3};
问题是,ItemToStringConverter.Convert 方法现在传递一个字符串对象作为第一个参数,而不是一个项目对象?
我究竟做错了什么?
问候,肯尼斯