c# - DependencyProperty 中的属性已更改

标签 c# wpf dependency-properties

previous post中我问如何将属性注册为 DependencyProperty。我得到了答案并且效果很好。

但现在我想在单击时向此 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)
    {

    }

当我将 XAML 绑定(bind)到 C# 代码时,将调用 OnChartEntriesChanged-Event。但是,如果我随后添加 ChartEntry(单击按钮时),则不会触发该事件。

有谁知道为什么吗?

最佳答案

当您将项目添加到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了解更多信息。

关于c# - DependencyProperty 中的属性已更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19558862/

相关文章:

c# - Azure Pipelines Nuget 还原失败 MSB4226

c# - ElasticSearch电子邮件地址,带有特殊字符,例如@

c# - WPF 文本进入和退出过渡效果

wpf - ViewModel 构造函数包含 WPF 中的参数

c# - WPF 绑定(bind)到文本框不更新

c# - 使用反射(Type.GetProperties)获取 DependencyProperties?

WPF:XAML 属性声明不是通过 Setter 设置的?

c# - 错误 : Object reference not set to an instance of an object

wpf - 在 WPF 按钮中显示点对点进度

c# - Linq 到实体 : Unions + Distinct