1、Model里面的数据对界面发出通知,界面里面的对象发生了变化。所有的属性都这么一个事情,就这些事情放到Common文件中,在Common文件中创建NotiticationObject.cs类。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentMgrDemo.Common
{
//INotifyPropertyChanged:实现接口
public class NotiticationObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
//定义一个“RaisePropertyChanged”方法,让它发起请求,需要一个string参数,让它监听属性
/// <summary>
/// 发起请求
/// </summary>
/// <param name="propertyName">属性名称</param>
public void RaisePropertyChanged(string propertyName)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
2、新建ViewModels文件夹,在ViewModels文件夹中新建LoginViewMode.cs类。
using StudentMgrDemo.Common;
using StudentMgrDemo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentMgrDemo.ViewModels
{
//调用发起通知的“NotiticationObject”类,继承“NotiticationObject”类里面的“RaisePropertyChanged”方法
public class LoginViewModel : NotiticationObject
{
//说明Login实体类
private Login loginObj = new Login();
//定义构造函数
public LoginViewModel()
{
loginObj.UserName = "admin";
}
public string UserName
{
get { return loginObj.UserName; }
set
{
loginObj.UserName = value;
this.RaisePropertyChanged("UserName");
}
}
}
}
3、LoginViewMode.cs和Logn.xaml的用户名绑定,通过this.DataContext=new LoginViewMode();
在Login.xaml绑定属性
执行结果: