WPF - DependencyProperty ignoring setter with side-effects on change
本问题已经有最佳答案,请猛点这里访问。
我有一个 WPF 用户控件,它是另外两个控件的package器,根据情况只显示其中一个。它拥有一个
我创建了一个
我怎样才能让底层控件在依赖属性更改时设置其属性?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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); } } } |
您必须将 propertyChangedCallback 传递给您的 UIPropertyMetadata,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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); } } |