DependencyProperty中的属性已更改 [英] Property Changed in DependencyProperty

查看:93
本文介绍了DependencyProperty中的属性已更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上一篇文章中,我问如何将属性注册为DependencyProperty。我得到了答案,并且工作正常。

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

但是,现在我想在单击上向此DependencyProperty添加一些项。这行不通。我注册DependencyProperty的代码是:

But now I want to add some Items to this DependencyProperty on a Click. This doesn't work. My code to register the DependencyProperty is:

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

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

    }

在执行从XAML到c#代码的绑定时,会调用OnChartEntriesChanged-Event。但是,如果我之后(单击按钮)添加ChartEntry,则不会触发该事件。

The OnChartEntriesChanged-Event is called at the moment I do the Binding from my XAML to my c#-code. But if I add a ChartEntry afterwards (on button-click) the event is not fired.

有人知道为什么吗?

推荐答案

将项目添加到 ChartEntries 集合时,您不要实际更改属性,因此不会调用PropertyChangedCallback。为了获得有关集合中更改的通知,您需要注册一个附加的 CollectionChanged 事件处理程序:

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






不要使用 ObservableCollection< ChartEntry> 作为属性类型,但只需 ICollection IEnumerable 代替。这将允许在具体集合类型中使用 INotifyCollectionChanged 的其他实现。请参见此处此处 a>有关更多信息。


It would also make sense not to use ObservableCollection<ChartEntry> 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.

这篇关于DependencyProperty中的属性已更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆