我有一个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);
}
}
}
答案 0 :(得分:1)
您必须将propertyChangedCallback传递给您的UIPropertyMetadata,如下所示:
public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register(
"ItemsSource", typeof(IEnumerable), typeof(AccountSelector), new UIPropertyMetadata((d, e) =>
{
if (e.NewValue == null) return;
var s = d as AccountSelector;
var list = e.NewValue as IEnumerable;
if (list == null || s == null) return;
if (s.UseComboBox)
s.AccCombo.ItemsSource = list;
else
s.AccComplete.ItemsSource = list;
}));
public IEnumerable ItemsSource
{
get
{
return (IEnumerable)GetValue(ItemsSourceProperty);
}
set
{
SetValue(ItemsSourceProperty, value);
}
}