【问题标题】:How to Override PropertyChangedCallback of a predefined Dependency Property ItemsSource in a WPF ItemsControl如何覆盖 WPF ItemsControl 中预定义的依赖属性 ItemsSource 的 PropertyChangedCallback
【发布时间】:2016-09-19 06:07:05
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • ItemsControl.OnItemsSourceChanged。这在ItemsSource 依赖控件的属性更改回调中调用。这可能不一定是你要找的……
  • @poke 你能指导我,如何监控Collection 更改...
  • 你可能有更多的运气观察 Items 属性的变化msdn.microsoft.com/en-us/library/… 它实现了 CollectionView 并因此有 CollectionChanged 事件。我不知道它会如何运作。它说 Items 集合在设置 ItemsSource 时是只读的。

标签: c# wpf dependency-properties itemscontrol propertychangelistener


【解决方案1】:

在派生的 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
    }
}

【讨论】:

    猜你喜欢
    • 2019-04-17
    • 2022-11-27
    • 2013-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多