-2

如何覆盖 WPF 中PropertyChangedCallback预定义的依赖属性。ItemsSourceItemsControl

我开发了一个继承自ItemsControl. 我使用了预定义的 Dependency Property ItemsSourceCollection因为一旦更新,我需要监控和检查数据。

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

https://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.itemssource(v=vs.110).aspx

请帮助我,覆盖的方法名称是什么?...

4

1 回答 1

3

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

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
    }
}
于 2016-09-19T06:43:44.190 回答