【发布时间】:2015-04-01 13:33:04
【问题描述】:
我有一个 WPF 用户控件,它是另外两个控件的包装器,根据情况只显示其中一个。它拥有一个ItemsSource 属性,该属性为两个底层控件设置ItemsSource。我想让这个属性可以绑定到一个 .xaml 文件。
我创建了一个DependencyProperty,并更改了我的getter 和setter 以使用它。但是,当我调试代码时,我可以看到 setter 永远不会被调用。我可以看到依赖属性正在改变它的值,但它没有设置底层控件的属性。
我怎样才能让底层控件在依赖属性更改时设置其属性?
public partial class AccountSelector : UserControl
{
public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register(
"ItemsSource", typeof(IEnumerable), typeof(AccountSelector));
public IEnumerable ItemsSource
{
get
{
return (IEnumerable)GetValue(ItemsSourceProperty);
}
set
{
if (UseComboBox)
AccCombo.ItemsSource = value;
else
AccComplete.ItemsSource = value;
SetValue(ItemsSourceProperty, value);
}
}
}
【问题讨论】:
-
属性的值是否已设置但可能不会被提升到 UI?此外,您将属性声明为只读,这将阻止分配给它,除非在同一类的构造函数或声明中。有关只读的更多信息,请参阅here。
标签: c# wpf data-binding wpf-controls