原創(chuàng)|使用教程|編輯:我只采一朵|2016-03-17 11:55:28.000|閱讀 3864 次
概述:BindableBase類提供 INotifyPropertyChanged 接口還有GetProperty 、 SetProperty方法。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關(guān)鏈接:
你也可以 下載Universal安裝包 或者到 查看更多示例和教程哦
BindableBase類提供 INotifyPropertyChanged 接口還有GetProperty 、 SetProperty方法。
public class ViewModel : BindableBase { public string FirstName { get { return GetProperty(() => FirstName); } set { SetProperty(() => FirstName, value); } } }
GetProperty 和 SetProperty方法的第一個參數(shù)是一個lamda表達(dá)式,用于識別目標(biāo)屬性名。屬性值存儲在一個內(nèi)部Dictionary中(GetProperty方法用這個詞典去獲取這個屬性的一個值,SetProperty根據(jù)屬性名存儲屬性值)。這種方法可以簡化代碼并且支持代碼檢查。
SetProperty方法返回True or False表示是否屬性被成功更改。有些SetProperty方法超載時仍然會返回一個callback方法作為參數(shù)。這個回調(diào)是在字段發(fā)生改變時才調(diào)用的。
public class ViewModel : BindableBase { public string FirstName { get { return GetProperty(() => FirstName); } set { SetProperty(() => FirstName, value, OnFirstNameChanged); } } void OnFirstNameChanged() { //... } }
如果你需要手動將INotifyPropertyChanged.PropertyChanged事件指定給某個屬性,用RaisePropertyChanged/RaisePropertiesChanged方法。
public class ViewModel : BindableBase { public string FullName { get { return string.Format("{0} {1}", FirstName, LastName); } } public string FirstName { get { return GetProperty(() => FirstName); } set { SetProperty(() => FirstName, value, OnFirstNameChanged); } } public string LastName { get { return GetProperty(() => LastName); } set { if(SetProperty(() => LastName, value)) RaisePropertyChanged(() => FullName); } } void OnFirstNameChanged() { RaisePropertyChanged(() => FullName); } }
在少數(shù)情況下,如果一個屬性頻繁更新,應(yīng)用程序性能會嚴(yán)重受損(因為要不斷計算lambda表達(dá)式的屬性名,不斷訪問詞典)。要解決這個問題,使用屬性的存儲變量并用 BindableBase.GetPropertyName<T> 方法計算屬性名。
public class ViewModel : BindableBase { static string Property1Name; static ViewModel() { Property1Name = BindableBase.GetPropertyName(() => new ViewModel().Property1); } string property1; public string Property1 { get { return property1; } set { SetProperty(ref property1, value, Property1Name); } } }
本站文章除注明轉(zhuǎn)載外,均為本站原創(chuàng)或翻譯。歡迎任何形式的轉(zhuǎn)載,但請務(wù)必注明出處、不得修改原文相關(guān)鏈接,如果存在內(nèi)容上的異議請郵件反饋至chenjj@fc6vip.cn