我是靠谱客的博主 优美小兔子,这篇文章主要介绍WPF总结INotifyPropertyChanged用法,现在分享给大家,希望可以做个参考。

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

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

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

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

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

最后

以上就是优美小兔子最近收集整理的关于WPF总结INotifyPropertyChanged用法的全部内容,更多相关WPF总结INotifyPropertyChanged用法内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(111)

评论列表共有 0 条评论

立即
投稿
返回
顶部