【发布时间】:2021-02-04 06:30:25
【问题描述】:
我创建了具有通用集合依赖属性的自定义控件。 但是,每当此属性从 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
【问题讨论】:
-
您还没有向我们展示“从 xaml 更改”的确切含义。有没有像
A="{Binding CollectionB, Mode=TwoWay}"这样的绑定?以及控件是如何改变集合的? -
绑定是 A="{Binding CollectionB, Mode=OneWayToSource}"
-
默认值(请参阅我在答案中的备注)类型为
List<object>。这不能分配给List<B>类型的源属性。 OneWayToSource 在这里不是一个非常适合的方法。根本不要设置默认值,而是使用双向绑定。 -
@AdamStawarek:当然,您可以将
IList属性设置为List<A>。如果属性仍然是null,那么你在设置它时做错了,或者你没有设置它。没有一些示例代码很难说。
标签: c# wpf dependency-properties