【问题标题】:Dependency Properties, change notification and setting values in the constructor依赖属性,在构造函数中更改通知和设置值
【发布时间】:2010-06-12 12:40:05
【问题描述】:

我有一个具有 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);
    }
}

【问题讨论】:

    标签: c# dependency-properties change-notification


    【解决方案1】:

    你可以试试这个吗?

    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); 
    } 
    

    【讨论】:

    • 非常感谢,证明是最好的答案(连同 VoodooChilds 的答案,我刚刚接受了这个,因为它包含一个代码示例)。
    【解决方案2】:

    使用DependencyObject.SetValueBase。这会绕过指定的任何元数据,因此不会调用您的 propertyChanged。见msdn

    【讨论】:

    • 非常感谢您的回复,这看起来很有希望,但是在智能感知中没有这个方法,只有 SetValue ? (使用 VS 2010、.NET 4)
    • 嗯,这似乎在 System.Workflow.DependencyObject 中。所以可能是错误的方向:/ meh.
    【解决方案3】:

    除非设置了所有三个属性,否则您不想执行 recalculate(),但是在设置 a、b 和 c 时它会从构造函数中调用?这是正确的吗?

    如果是这样,您能否只在顶部附近的重新计算中进行检查以检查所有三个属性是否已设置并决定是否要执行......

    这会起作用,因为你提到了

    因为方法 recalculate() 不能做 没有全部3的任何真正有用的东西 属性集。

    【讨论】:

    • 感谢 VoodooChild,这确实可行,但是我想知道是否有更好的解决方案/模式。 Femaref 答案看起来是完美的解决方案,我只是不明白如何使用 SetValueBase。
    猜你喜欢
    • 2010-12-02
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    相关资源
    最近更新 更多