![](/img/trans.png)
[英]Elegant way to implement INotifyPropertyChanged across many controls
[英]Implement many INotifyPropertyChanged
請告訴我實現許多重復INotifyPropertyChanged的最佳方法。 我有一個有10個孩子的MainClass,每個孩子有6個字段,並且每個字段必須在更改自身值時觸發屬性更改。 這是我的代碼,但不起作用:
public class BaseModel
{
public string S1 { get; set; }
public string S2 { get; set; }
public string S3 { get; set; }
public string S4 { get; set; }
public string S5 { get; set; }
public string S6 { get; set; }
}
我使用一個名為ViewModelBase的類來實現INotifyPropertyChanged。 在第二步中,使用一個類來實現重復的INotifyPropertyChanged:
public class ImplementBaseModel : ViewModelBase
{
private readonly BaseModel _baseModel;
public ImplementBaseModel()
{
_baseModel = new BaseModel();
}
public string S1
{
get { return _baseModel.S1; }
set
{
if (_baseModel.S1 == value)
return;
_baseModel.S1 = value;
base.OnPropertyChanged("S1");
}
}
public string S2
{
get { return _baseModel.S2; }
set
{
if (_baseModel.S2 == value)
return;
_baseModel.S1 = value;
base.OnPropertyChanged("S2");
}
}
// other code...
}
那么一個模型有10個此類:
public class MidClass
{
public ImplementBaseModel ImplementBaseModel1 { get; set; }
public ImplementBaseModel ImplementBaseModel2 { get; set; }
// other field
public ImplementBaseModel ImplementBaseModel10 { get; set; }
public MidClass()
{
ImplementBaseModel1 = new ImplementBaseModel();
ImplementBaseModel2 = new ImplementBaseModel();
// ....
ImplementBaseModel10 = new ImplementBaseModel();
}
}
OK完成代碼! 現在,請告訴我為什么價值變動時某些財產沒有被解雇? 是實現此代碼的最佳方法?
在設置員中,您實際上從未設置過該值。 采用:
public string S1
{
get { return _baseModel.S1; }
set
{
if (_baseModel.S1 == value)
return;
baseModel.S1 = value;
OnPropertyChanged("S1");
}
}
請注意,我從OnPropertyChanged中刪除了base
。 以這種方式調用PropertyChanged事件是不正常的。
NotifyPropertyChanged所做的所有操作是使每個綁定對其綁定屬性執行“獲取”。 如果支持字段從未更新過,它們將僅獲得相同的數據。
作為快捷方式,您還可以創建一個本地方法,例如
bool UpdateAndRaiseIfNecessary( ref string baseValue, string newValue, [CallerMemberName] string propertyName = null)
{
if (baseValue != newValue)
{
baseValue = newValue;
OnPropertyChanged( propertyName );
return true;
}
return false;
}
然后所有的二傳手都會是這樣的:
set
{
this.UpdateAndRaiseIfNecessary( ref _baseModel.S1, value );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.