PropertyChanged WPF MVVM 光

PropertyChanged WPF MVVM Light

我在 WPF 中使用 MVVM light。由于底层数据访问层的变化,模型 class 属性不断变化。

型号:

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;
     }
   }
 }

为什么 connectionhelper 中的 RaisePropertyChanged 调用不更新模型的 属性?如果这是错误的方式,我应该设置某种监听器吗?

您应该只在 ViewModel 中使用 属性Changed,而不是在模型中。 您可以使用 属性仅在特殊时期更改模型。

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

在 属性Changed 中,您总是说输出 属性 已更改。

我建议你实施 INotify属性Changed

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");

在您的 SBE_V1_Model class 中,您应该订阅以接收来自 ConnectionHelper ViewModel 的 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。这是您可能对 Whosebug 感兴趣的 link