如何覆盖WPF ItemsControl中预定义的依赖项属性ItemsSource的PropertyChangedCallback

时间:2016-09-19 06:07:05

标签: c# wpf dependency-properties itemscontrol propertychangelistener

如何覆盖 PropertyChangedCallback WPF ItemsSource中预定义的依赖属性 ItemsControl

我开发了一个继承自 ItemsControl 的WPF自定义控件。我使用了预定义的依赖属性 ItemsSource 。我需要在 Collection 更新后监控并检查数据。

我在谷歌搜索了很多,但我无法找到任何相关的解决方案来满足我的要求。

http://codepen.io/PiotrBerebecki/pen/vXXXaJ

请帮助我,方法名称是否覆盖? ...

1 个答案:

答案 0 :(得分:2)

在派生的ItemsSource类的静态构造函数中调用OverrideMetadata

public class MyItemsControl : ItemsControl
{
    static MyItemsControl()
    {
        ItemsSourceProperty.OverrideMetadata(
            typeof(MyItemsControl),
            new FrameworkPropertyMetadata(OnItemsSourcePropertyChanged));
    }

    private static void OnItemsSourcePropertyChanged(
        DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        ((MyItemsControl)obj).OnItemsSourcePropertyChanged(e);
    }

    private void OnItemsSourcePropertyChanged(DependencyPropertyChangedEventArgs e)
    {
        var oldCollectionChanged = e.OldValue as INotifyCollectionChanged;
        var newCollectionChanged = e.NewValue as INotifyCollectionChanged;

        if (oldCollectionChanged != null)
        {
            oldCollectionChanged.CollectionChanged -= OnItemsSourceCollectionChanged;
        }

        if (newCollectionChanged != null)
        {
            newCollectionChanged.CollectionChanged += OnItemsSourceCollectionChanged;
            // in addition to adding a CollectionChanged handler
            // any already existing collection elements should be processed here
        }
    }

    private void OnItemsSourceCollectionChanged(
        object sender, NotifyCollectionChangedEventArgs e)
    {
        // handle collection changes here
    }
}