在WPF中,View和ViewModel是分离的,View可以认为是UI层,ViewModel可以认为是数据层,若想实现数据驱动UI,将ViewModel中的值更新给View,VM对象需实现INotifyPropertyChanged接口,通过事件来通知UI。INotifyPropertyChanged 接口用于向客户端(通常是执行绑定的客户端)发出某一属性值已更改的通知。
以Textbox为例,通过INotifyPropertyChanged实现数据更新。
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的分离,也会降低的程序编写的效率,同时增加了代码的耦合度。