PropertyChanged WPF MVVM Light

时间:2015-12-12 19:20:47

标签: c# wpf mvvm inotifypropertychanged

我在WPF中使用MVVM灯。由于底层数据访问层的更改,Model类属性不断更改。

型号:

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调用不会更新模型的属性?如果这是错误的方式,我应该设置一些听众吗?

2 个答案:

答案 0 :(得分:0)

您应该只在视图模型中使用PropertyChanged,而不是在Model中。 您可以在特殊时间仅在模型中使用PropertyChange。

docker run -p 3000:3000 -d rails server -p 3000 -b 0.0.0.0

在那个PropertyChanged中,你正在说输出属性已经改变了。

我建议你实现INotifyPropertyChanged

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

要通知您必须使用的任何财产变更:

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

    }

答案 1 :(得分:0)

SBE_V1_Model课程中,您应订阅从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光信使。以下是您可能对StackOverflow感兴趣的link