2010-06-12 37 views
3

我有一个包含3个依赖属性A,B,C的类。这些属性的值由构造函数设置,每次属性A,B或C中的一个发生更改时,都会调用recalculate()方法。现在在执行构造函数的过程中,这些方法被调用3次,因为A,B,C三个属性都被改变了。 Hoewever这不是必须的,因为如果没有设置所有3个属性,方法重新计算()不能做任何真正有用的操作。那么,什么是属性更改通知的最好方法,但在构造函数中绕过这个更改通知?我曾想过在构造函数中添加属性改变通知,但随后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); 
    } 
} 

回答

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

非常感谢你,被证明是最好的答案(与VoodooChilds答案一起,我只是接受了这个,因为它包含了一个代码示例)。 – 2010-07-05 13:45:05

1

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

+0

非常感谢您的回复,这看起来很有希望,但是在intellisense中没有这个方法,只有SetValue? (使用VS 2010,.NET 4) – 2010-06-12 13:01:20

+0

嗯,这似乎是在System.Workflow.DependencyObject。所以可能是错误的方向:/嗯。 – Femaref 2010-06-12 13:24:08

0

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

如果是这样,你能不能只把支票在重新计算接近顶部检查所有三个属性设置,并决定是否要执行或不....

这工作,因为你提到

的方法重新计算()不能做任何事情 没有所有3个 属性设置非常有用。

+0

感谢VoodooChild,这确实会起作用,但是如果有更好的解决方案/模式的话,我会赢。 Femaref答案看起来像完美的解决方案,我只是不明白如何能够使用SetValueBase。 – 2010-06-12 13:08:11