我有来自WPF Toolkit的IntegerUpDown,喜欢将它从实体框架绑定到自动生成的集合(EntityCollection)。
我的意图:我有这个UpDown控件来改变集合中的项目数。
我能够使用转换器在IntegerUpDown中显示Count,但不能更改集合中的项目数,因为我无法使用IValueConverter接口控制ConvertBack() - 函数的集合。 / p>
修改
但是我不能使用转换器来准确地解决这个问题。因为在ConvertBack()中,模型中的集合将被修改后的转换器类覆盖。这在EF中是不可能的。 我必须直接使用EF中的模型,修改项目。
答案 0 :(得分:2)
具有可设置计数的集合?那太不寻常了!无论如何,您要做的是向您的viewmodel添加MyCollectionCount
属性并绑定到该属性:
public int MyCollectionCount
{
get { return Model.MyCollection != null ? Model.MyCollection.Count : 0 ; }
set { if (Model.MyCollection != null)
Model.MyCollection.Count = value ; /* ¬_¬ */ }
}
答案 1 :(得分:1)
如果您的控件正在使用数据绑定,您可以将其作为参数传递给convert:
<IntegerUpDown Value="{Binding MyCollection,
Converter={StaticResource CollectionConverter},
ConverterParameter=MyCollection}" />
并将其用作转换器:
public class UpDownConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
ICollection<Type> col = (ICollection<Type>)value;
return col.Count;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
ICollection<Type> col = (ICollection<Type>)parameter;
// Do manipulation here
}
}
有关Xaml中转换器的更多信息,请check out the MSDN。