[英]PropertyChanged WPF MVVM Light
我在WPF中使用MVVM light。 由於基礎數據訪問層的更改,因此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
調用不更新模型的屬性? 如果這是錯誤的方法,我應該設置某種偵聽器嗎?
您僅應在視圖模型中使用PropertyChanged,而不能在模型中使用。 您只能在特殊時間使用Model中的PropertyChange。
RaisePropertyChanged("Output", false,b, true);
在那個PropertyChanged中,您總是說輸出屬性已更改。
我建議您實現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");
在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感興趣的鏈接 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.