2015-12-12 183 views
0

我在WPF中使用MVVM light。 Model類屬性由於底層數據訪問層的變化而不斷變化。PropertyChanged WPF MVVM Light

型號:

public class SBE_V1_Model : ViewModelBase 
{ 
    public SBE_V1_Model(String name) 
    { 
     Name = "MAIN." + name; 
     SetupClient(); 
    } 
    private void SetupClient() 
    { 
     client = new ConnectionHelper(this); 
     client.Connect(Name); 

    } 
    public Boolean Output 
    { 
     get 
     { 
      return _Output; 
     } 
     set 
     { 
      if (value != this._Output) 
      { 
       Boolean oldValue = _Output; 
       _Output = value; 
       RaisePropertyChanged("Output", oldValue, value, true); 
      } 
     } 
    } 
} 

如果Output屬性發生變化,那麼綁定將被通知,所以此工程。但是,從知道新值的數據訪問源更新屬性的正確方法是什麼?

public class ConnectionHelper : ViewModelBase 
{ 
    public Boolean Connect(String name) 
    { 
     Name = name; 
     tcClient = new TcAdsClient(); 

     try 
     { 
      dataStream = new AdsStream(4); 
      binReader = new AdsBinaryReader(dataStream); 
      tcClient.Connect(851); 
      SetupADSNotifications(); 
      return true; 
     } 
     catch (Exception ee) 
     { 
      return false; 
     } 
    } 
    private void tcClient_OnNotification(object sender, AdsNotificationEventArgs e) 
    { 
     String prop; 
     notifications.TryGetValue(e.NotificationHandle, out prop); 
     switch (prop) 
     { 
      case "Output": 
       Boolean b = binReader.ReadBoolean(); 
       RaisePropertyChanged("Output", false,b, true); 
       break; 
    } 
    } 
} 

爲什麼犯規的RaisePropertyChanged呼叫connectionhelper更新模型的財產?如果這是錯誤的方式,我應該設立某種聽衆嗎?

回答

0

在你SBE_V1_Model類,你應該訂閱從ConnectionHelper收到的PropertyChange通知視圖模型。

// Attach EventHandler 
ConnectionHelper.PropertyChanged += OnConnectionHelperPropertyChanged; 

... 

// When property gets changed, raise the PropertyChanged 
// event of the ViewModel copy of the property 
OnConnectionHelperPropertyChanged(object sender, PropertyChangedEventArgs e) 
{ 
    if (e.PropertyName == "Something") //your ConnectionHelper property name 
     RaisePropertyChanged("Ouput"); 
} 

另請參閱MVVM light messenger。這裏是您可能會從StackOverflow感興趣的link

0

您應該只在視圖模型中使用PropertyChanged,而不是在Model中使用PropertyChanged。 只能在特殊時間在模型中使用PropertyChange。

RaisePropertyChanged("Output", false,b, true); 

在那個PropertyChanged中,你是alwais說輸出屬性被改變了。

我建議你實現INotifyPropertyChanged

class MyClass : INotifyPropertyChanged 
    { 
     public bool MyProperty{ get; set; } 

     public event PropertyChangedEventHandler PropertyChanged; 

     protected void OnPropertyChanged(string name) 
     { 
     PropertyChangedEventHandler handler = PropertyChanged; 
     if (handler != null) 
     { 
      handler(this, new PropertyChangedEventArgs(name)); 
     } 
     } 

    } 

通知您必須使用任何屬性變化:

OnPropertyChanged("MyProperty");