DevExpress控件使用交流,DevExpress中国社区Dev联系电话 联系电话:023-68661681

DevExpress WPF基础教程:MVVM框架之BindableBase类

来源:   发布时间:2016-08-02   浏览:3865次

你也可以 下载Universal安装包 查看更多示例


BindableBase

BindableBase类提供 INotifyPropertyChanged 接口还有GetProperty 、 SetProperty方法。

public class ViewModel : BindableBase {
public string FirstName {
get { return GetProperty(() => FirstName); }
set { SetProperty(() => FirstName, value); }
}
}

GetProperty 和 SetProperty方法的第一个参数是一个lamda表达式,用于识别目标属性名。属性值存储在一个内部Dictionary中(GetProperty方法用这个词典去获取这个属性的一个值,SetProperty根据属性名存储属性值)。这种方法可以简化代码并且支持代码检查。

SetProperty方法返回True or False表示是否属性被成功更改。有些SetProperty方法超载时仍然会返回一个callback方法作为参数。这个回调是在字段发生改变时才调用的。

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

在少数情况下,如果一个属性频繁更新,应用程序性能会严重受损(因为要不断计算lambda表达式的属性名,不断访问词典)。要解决这个问题,使用属性的存储变量并用 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); }
}
}

======================================================================

DevExpress专为企业客户提供团队、企业授权优惠方案,欢迎来电咨询:023-66090381

DevExpress企业集团授权

本站文章除注明转载外,均为本站原创或翻译
欢迎任何形式的转载,但请务必注明出处,尊重他人劳动成果
转载请注明:文章转载自:DevExpress控件中文网 [https://www.devexpresscn.com/]
本文地址:https://www.devexpresscn.com/post/703.html

相关产品: DevExpress Universal Subscription,

在线
客服
微信
QQ 电话
023-68661681
返回
顶部