[英]Wpf: Generic collection dependency property
我已经创建了具有通用集合依赖属性的自定义控件。 但是每当此属性从 xaml 更改时,setter 中视图模型中的值为 null。
自定义控件:
public IList A
{
get { return (IList)GetValue(AProperty); }
set { SetValue(AProperty, value); }
}
public static readonly DependencyProperty AProperty =
DependencyProperty.Register(nameof(A), typeof(IList), typeof(CustomControl), new PropertyMetadata(new List<object>()));
视图模型:
List<B> collectionB;
public List<B> CollectionB
{
get { return collectionB; }
set
{
if (collectionB == value) return;
collectionB = value;
}
}
如果我将 CollectionB 的类型更改为 List<object> 它工作正常。
集合属性的最通用类型是IEnumerable
- 例如,参见ItemsControl.ItemsSource
属性。
另请注意,为集合类型依赖项属性设置非空默认值是有问题的,因为默认情况下,所属类的所有实例都会对同一个集合实例进行操作。 将元素添加到一个控件的 A 属性将更改所有其他控件实例的集合。
您应该像这样声明属性:
public IEnumerable A
{
get { return (IEnumerable)GetValue(AProperty); }
set { SetValue(AProperty, value); }
}
public static readonly DependencyProperty AProperty =
DependencyProperty.Register(
nameof(A), typeof(IEnumerable), typeof(CustomControl));
如果您确实需要一个非空的默认值,请将其添加到控件的构造函数中:
SetCurrentValue(AProperty, new List<object>());
更新:使用集合类型属性的OneWayToSource
绑定,例如
<local:CustomControl A="{Binding CollectionB, Mode=OneWayToSource}" />
仅当A
的默认值与 Binding 的源属性赋值兼容时才能工作,这不适用于List<object>
和List<B>
。
您根本不应设置默认值,而应使用双向绑定
<local:CustomControl A="{Binding CollectionB, Mode=TwoWay}" />
和
private List<B> collectionB = new List<B>();
public List<B> CollectionB
{
get { return collectionB; }
set { collectionB = value; }
}
要不就
public List<B> CollectionB { get; set; } = new List<B>();
那是因为IList<T>
没有实现IList
所以从一种类型转换到另一种类型会失败。
如果你想要一个与A
的绑定,那么你必须将它绑定到同样实现IList
东西
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.