在自定义控件中,当IEnumerable类型的DepenencyProperty发生更改时收到通知

时间:2014-10-23 16:13:35

标签: c# wpf xaml binding

我正在使用自定义WPF UserControl并且遇到了一个DependencyProperties问题。

所以我构建了一个看起来像这样的测试场景。在自定义控件..

public static readonly DependencyProperty MyCollectionItemsSourceProperty = DependencyProperty.Register("DynamicHeaderItemsSource", typeof(IEnumerable), typeof(TestUserControl1),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender, new PropertyChangedCallback(OnMyCollectionItemsSourceChanged))); 

public IEnumerable MyCollectionItemsSource
{
    get { return (IEnumerable)GetValue(MyCollectionItemsSourceProperty ); }
    set { SetValue(MyCollectionItemsSourceProperty , value); }
}

protected static void OnMyCollectionItemsSourceChanged(DependencyObject property, DependencyPropertyChangedEventArgs args)
{
    System.Diagnostics.Debug.WriteLine("MyCollection Updated");           
}

在我的测试窗口代码背后:

public ObservableCollection<string> MyTestStrings { get; set; }

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    MyTestStrings.Add("First");
    MyTestStrings.Add("Second");
    MyTestStrings.Add("Third");
}

在我的测试窗口中XAML:

<Grid>
    <local:TestUserControl1 MyCollectionItemsSource="{Binding MyTestStrings}">
</Grid>

问题是,当下划线集合发生变化时,我从未收到任何类型的通知。 OnMyCollectionItemsSourceChanged只被调用一次:在设置绑定时开始。我错过了什么?

2 个答案:

答案 0 :(得分:2)

当MyCollectionItemsSource在XAML绑定中设置时,它是一个预期的行为,因为(一次)集合中的这些添加不会改变您的属性本身(它正在集合中执行某些操作)。 如果你想获得有关更改集合的信息,你必须首先在OnMyCollectionItemsSourceChanged事件测试中,如果该值支持INotifyCollectionChanged,那么注册NotifyCollectionChangedEventHandler isndie,不要忘记取消注册你的处理程序

  protected static void OnMyCollectionItemsSourceChanged(DependencyObject property, DependencyPropertyChangedEventArgs args)
    {
        if( args.OldValue is INotifyCollectionChanged)
           (args.OldValue as INotifyCollectionChanged ).CollectionChanged -= CollectionChangedHandler;
       if(args.NewValue is INotifyCollectionChanged)
           (args.OldValue as INotifyCollectionChanged).CollectionChanged += CollectionChangedHandler;

    }

    private static void CollectionChangedHandler(object sender, NotifyCollectionChangedEventArgs e)
    {
      //
    }

答案 1 :(得分:1)

仅当属性设置(或无效)时才会调用PropertyChangedCallback,而不是集合本身有任何更改(添加/删除元素)。为此,您必须连接到CollectionChanged事件。请参阅此帖子:https://stackoverflow.com/a/12746855/4173996

相关问题