zoukankan      html  css  js  c++  java
  • WP学习笔记(5)MVVM入门 第二部分DependencyProperty

    上篇用INotifyPropertyChanged实现的属性变更通知UI,在这篇里我们看看使用DependencyProperty如何实现。

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

     1 public class WeatherViewModel : DependencyObject
     2     {
     3         public WeatherViewModel()
     4         {
     5             if (updateCmd == null)
     6             {
     7                 updateCmd = new UpdateCmd(this);
     8             }
     9         }
    10         public ICommand updateCmd { get; private set; }
    11         public static readonly DependencyProperty cityProperty = DependencyProperty.Register("city", typeof(string), typeof(WeatherViewModel), null);
    12         public string city
    13         {
    14             get { return (string)GetValue(cityProperty); }
    15             set { SetValue(cityProperty, value); }
    16         }
    17     }

    调试一下和上次一样的结果。不一样的地方在于上次使用的是一个普通属性,我们在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中对依赖属性的描述,依赖项属性为值表达式、数据绑定、动画和属性更改通知提供支持。其他几项还没研究过,路漫漫其修远,吾将上下求索吧。欢迎有研究的大神指点一二,共同进步。

  • 相关阅读:
    Git
    Qcon2016上海站PPT
    TeamCity
    在cmd界面,怎么样退出Node.js运行环境
    python 2.x与python3.x的区别
    d3.max()与d3.min()
    d3.svg.line() 曲线构造器
    d3.js 之SVG:矢量化图形绘制
    moment.js 时间格式化库
    directive
  • 原文地址:https://www.cnblogs.com/titans110/p/3184199.html
Copyright © 2011-2022 走看看