2013-10-24 68 views
2

previous post我问如何注册属性作为DependencyProperty。我有一个答案,它工作正常。属性更改依赖属性

但是现在我想在Click上添加一些项目到这个DependencyProperty。这不起作用。我的代码注册的DependencyProperty是:

public static readonly DependencyProperty ChartEntriesProperty = DependencyProperty.Register(
     "ChartEntries", typeof(ObservableCollection<ChartEntry>), typeof(ChartView), 
     new FrameworkPropertyMetadata(OnChartEntriesChanged)); 

    private static void OnChartEntriesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
    { 

    } 

的OnChartEntriesChanged-事件被称为在我从我的XAML绑定到我的C#-code的时刻。但是,如果我以后添加ChartEntry(按钮单击)事件不会被解雇。

有谁知道为什么?

回答

4

当您添加一个项目到ChartEntries集合,你实际上改变的财产,所以PropertyChangedCallback不叫。为了收到通知集合中的变化,你需要注册一个额外CollectionChanged事件处理程序:

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) 
{ 
    ... 
} 

这也将使意义,不使用ObservableCollection<ChartEntry>的属性类型,而只是ICollectionIEnumerable代替。这将允许具体集合类型中的INotifyCollectionChanged的其他实现。有关更多信息,请参阅herehere

0

对不起,但这不会像你发现自己一样。 DependencyProperty更改处理程序只会触发,如果属性的值发生更改,但在您的情况下它不会,因为对象引用仍然是相同的。您必须在提供的集合的CollectionChanged事件处理程序上注册。 (这个你可以从的DependencyProperty的PropertyChanged处理程序做)

1

OnChartEntriesChanged当您将设置ObservableCollection的新实例时,将会调用回调。您将不得不收听收藏变更如下:

private static void OnChartEntriesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
    { 
     ((ObservableCollection<ChartView>)e.OldValue).CollectionChanged -= new System.Collections.Specialized.NotifyCollectionChangedEventHandler(ChartView_CollectionChanged); 
     ((ObservableCollection<ChartView>)e.NewValue).CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(ChartView_CollectionChanged); 
    } 

    static void ChartView_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) 
    { 

    }