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