c# - 构造函数中的依赖属性、更改通知和设置值

标签 c# dependency-properties change-notification

我有一个具有 3 个依赖属性 A、B、C 的类。这些属性的值由构造函数设置,每次属性 A、B 或 C 之一更改时,都会调用方法 recalculate()。现在在构造函数的执行过程中,这些方法被调用了 3 次,因为 3 个属性 A、B、C 被更改了。但这不是必需的,因为如果没有设置所有 3 个属性,方法 recalculate() 将无法做任何真正有用的事情。那么,除了在构造函数中规避此更改通知之外,属性更改通知的最佳方式是什么?我考虑过在构造函数中添加属性更改通知,但随后 DPChangeSample 类的每个对象总是添加越来越多的更改通知。感谢您的任何提示!

class DPChangeSample : DependencyObject
{                  
    public static DependencyProperty AProperty = DependencyProperty.Register("A", typeof(int), typeof(DPChangeSample), new PropertyMetadata(propertyChanged));
    public static DependencyProperty BProperty = DependencyProperty.Register("B", typeof(int), typeof(DPChangeSample), new PropertyMetadata(propertyChanged));
    public static DependencyProperty CProperty = DependencyProperty.Register("C", typeof(int), typeof(DPChangeSample), new PropertyMetadata(propertyChanged));


    private static void propertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        ((DPChangeSample)d).recalculate();
    }


    private void recalculate()
    {
        // Using A, B, C do some cpu intensive calculations
    }


    public DPChangeSample(int a, int b, int c)
    {
        SetValue(AProperty, a);
        SetValue(BProperty, b);
        SetValue(CProperty, c);
    }
}

最佳答案

你能试试这个吗?

private bool SupressCalculation = false;
private void recalculate() 
{ 
    if(SupressCalculation)
        return;
    // Using A, B, C do some cpu intensive caluclations 
} 


public DPChangeSample(int a, int b, int c) 
{
    SupressCalculation = true; 
    SetValue(AProperty, a); 
    SetValue(BProperty, b); 
    SupressCalculation = false;
    SetValue(CProperty, c); 
} 

关于c# - 构造函数中的依赖属性、更改通知和设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3028680/

相关文章:

Delphi:TJvChangeNotify/TShellChangeNotifier - 文件名

c# - 了解多项目(可互操作).NET 解决方案中的配置文件

c# - 如何更新 Azure 表存储中的实体?

wpf - 将 WPF UserControl 绑定(bind)到 View 模型和隐藏代码

wpf - INotifyPropertyChanged 与 ViewModel 中的 DependencyProperty

javascript - 当一个元素被添加到页面时,我如何得到通知?

c# - 不同命名空间中的部分类未被正确识别

c# - 在 JsonConvert.DeserializeObject 中反序列化对象时出现意外标记

Silverlight - 为什么要使用附加属性?

windows - 快速判断文件夹内容是否被修改