您的位置:首页 > 运维架构

WP学习笔记(5)MVVM入门 第二部分DependencyProperty

2013-07-11 16:24 253 查看
上篇用INotifyPropertyChanged实现的属性变更通知UI,在这篇里我们看看使用DependencyProperty如何实现。

需要改变的部分并不多,打开WeatherViewModel,修改WeatherViewModel类如下

public class WeatherViewModel : DependencyObject
{
public WeatherViewModel()
{
if (updateCmd == null)
{
updateCmd = new UpdateCmd(this);
}
}
public ICommand updateCmd { get; private set; }
public static readonly DependencyProperty cityProperty = DependencyProperty.Register("city", typeof(string), typeof(WeatherViewModel), null);
public string city
{
get { return (string)GetValue(cityProperty); }
set { SetValue(cityProperty, value); }
}
}


调试一下和上次一样的结果。不一样的地方在于上次使用的是一个普通属性,我们在viewmodel上实现了INotifyPropertyChanged接口,并且在更新属性时通知给UI;这次我们直接定义了一个依赖属性。要定义一个PropertyChanged需要通过DependencyProperty.Register方法,修饰符必须是public static readonly DependencyProperty并且名称结尾必须是Property。要操作这个DependencyProperty必须通过GetValue()和SetValue()方法。
既然我们有两种方式实现ViewModel中的变更通知,如何选择呢?

我参考了这两篇文章http://www.codeproject.com/Articles/62158/DependencyProperties-or-INotifyPropertyChanged

http://blog.quantumbitdesigns.com/2010/01/26/mvvm-lambda-vs-inotifypropertychanged-vs-dependencyobject/

如此看来这两种途径各有利弊,效率上DependencyProperty好,灵活性上INotifyPropertyChanged好。

msdn中对依赖属性的描述,依赖项属性为值表达式、数据绑定、动画和属性更改通知提供支持。其他几项还没研究过,路漫漫其修远,吾将上下求索吧。欢迎有研究的大神指点一二,共同进步。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐