2010-06-12 54 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