Property Changed in DependencyProperty

后端 未结 4 863
臣服心动
臣服心动 2020-12-07 04:37

In a previous post I asked how to register a property as DependencyProperty. I got an answer and it works fine.

But now I want to add some Items to this DependencyP

4条回答
  •  再見小時候
    2020-12-07 05:01

    When you add an item to the ChartEntries collection, you do not actually change that property, so the PropertyChangedCallback isn't called. In order to get notified about changes in the collection, you need to register an additional CollectionChanged event handler:

    private static void OnChartEntriesChanged(
        DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        var chartView = (ChartView)obj;
        var oldCollection = e.OldValue as INotifyCollectionChanged;
        var newCollection = e.NewValue as INotifyCollectionChanged;
    
        if (oldCollection != null)
        {
            oldCollection.CollectionChanged -= chartView.OnChartEntriesCollectionChanged;
        }
    
        if (newCollection != null)
        {
            newCollection.CollectionChanged += chartView.OnChartEntriesCollectionChanged;
        }
    }
    
    private void OnChartEntriesCollectionChanged(
        object sender, NotifyCollectionChangedEventArgs e)
    {
        ...
    }
    

    It would also make sense not to use ObservableCollection for the property type, but simply ICollection or IEnumerable instead. This would allow for other implementations of INotifyCollectionChanged in the concrete collection type. See here and here for more information.

提交回复
热议问题