当前位置:   article > 正文

WPF总结INotifyPropertyChanged用法_inotifypropertychanged如何通知界面

inotifypropertychanged如何通知界面

在WPF中,View和ViewModel是分离的,View可以认为是UI层,ViewModel可以认为是数据层,若想实现数据驱动UI,将ViewModel中的值更新给View,VM对象需实现INotifyPropertyChanged接口,通过事件来通知UIINotifyPropertyChanged 接口用于向客户端(通常是执行绑定的客户端)发出某一属性值已更改的通知。

以Textbox为例,通过INotifyPropertyChanged实现数据更新。

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.ComponentModel;
  7. namespace MVVM
  8. {
  9. [Serializable]
  10. public class PropertyChangedObj:INotifyPropertyChanged
  11. {
  12. public event PropertyChangedEventHandler PropertyChanged;
  13. public void OnPropertyChanged(string _property)
  14. {
  15. PropertyChangedEventHandler eventhandler = this.PropertyChanged;
  16. if (null == eventhandler)
  17. return;
  18. eventhandler(this, new PropertyChangedEventArgs(_property));
  19. }
  20. }
  21. }
  22. using System;
  23. using System.Collections.Generic;
  24. using System.Linq;
  25. using System.Text;
  26. using System.Threading.Tasks;
  27. using MVVM;
  28. namespace TextBoxDemo
  29. {
  30. class TextModel:PropertyChangedObj
  31. {
  32. #region TextValue
  33. public const string TextValueChanged = "TextValue";
  34. public int TextValue
  35. {
  36. get
  37. {
  38. return textValue;
  39. }
  40. set
  41. {
  42. if (value == textValue)
  43. return;
  44. textValue = value;
  45. RaisePropertyChanged(TextValueChanged);
  46. }
  47. }
  48. #endregion
  49. }
  50. }

定义一个抽象基类PropertyChangedObj实现INotifyProperChanged接口;定义ViewModel继承自PropertyChangedObj,这样就能使用RaisePropertyChange函数,当属性值发生变化的时候,在set中调用RaisePropertyChange函数。

一般不在xaml.cs中实现逻辑代码,这样不利于逻辑和UI的分离,也会降低的程序编写的效率,同时增加了代码的耦合度。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/567811
推荐阅读
  

闽ICP备14008679号