3、WPF_MVVM LoginViewModel.cs和Login.xaml用户名绑定

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绑定属性
在这里插入图片描述
执行结果:
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值