3

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

3 回答 3

1

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

于 2010-06-12T12:51:50.930 回答
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); 
} 
于 2010-06-12T14:24:20.177 回答
0

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

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

这将起作用,因为您提到了

因为如果没有设置所有 3 个属性,方法 recalculate() 就无法做任何真正有用的事情。

于 2010-06-12T12:59:08.277 回答