2011-06-02 56 views
1

非常常見的情況。我們有:MVVM模式基礎知識

double _H; 
public double H 
{ 
    get { return _H; } 
    set 
    { 
    if (_H == value) return; 
    _H = value; 
    SomeMethod("H");  
    //Inside SomeMethod's body we calculate some other properties among other things, 
    //and we call their corresponding base.RaisePropertyChanged. ALSO we 
    //RECALCULATE the freshly set H and we WANT to call base.RaisePropertyChanged("H") 
    //to "propagate" the changed value back to the View control that called the setter 
    //portion of the property in the first place! 
    } 
} 

答: 看周杰倫的帖子。關鍵的概念,以防止這個問題:異步調用如傑提到的。

一些更多的細節(可能是重複或無關):我有一個NumericUpDown控件,我點擊它的按鈕來改變它的值。問題是我想重新計算給定的值並查看是否允許(在視圖模型中進行驗證)。但我無法推回從控制權發送到財產的設定部分的價值。首先想到的解決方案是在視圖中觸發ValueChanged事件,並從那裏撥打SomeMethod("H")。雖然不好。

實際上,大約有10個NumericUpDown控件。每個值表示幾何形狀的尺寸。所以,一個值的變化可以改變其他維度。當計算確定剛剛給出的值也必須改變時(如果你明白我的意思),問題就出現了。 也有一些相關的XAML代碼:

<l:NumericUpDown Value="{Binding H}" Maximum="{Binding MaxSide, Mode=OneTime}" 
Grid.Column="7"/> 
+1

嘗試把'base.RaisePropertyChanged( 「H」)'計算爲'H'值的方法如下。 – aligray 2011-06-02 12:11:03

+0

@aligray不,它不是那麼簡單。它與綁定有關。問題在於控件不會通過'raisepropertychanged'得到通知,因爲它處於發送值的「模式」中。 'raisepropertychanged'只有在從另一個控件調用「設置部分」時才起作用,例如,一個獨立的按鈕。 – 2011-06-02 12:13:50

+0

是綁定到文本框的屬性? – aligray 2011-06-02 12:18:52

回答

4

您需要使用的調度要麼強制刷新或提高二傳(異步調用)的上下文之外的屬性更改通知。

所以,與其

base.OnPropertyChanged("H"); 

...你會怎麼做

Action action =() => base.OnPropertyChanged("H"); 
Dispatcher.CurrentDispatcher.BeginInvoke(action); 
+0

Yeap Jay !!!!!!它做到了。這就是爲什麼我愛StackOverflow! – 2011-06-02 13:26:52