在winform中,实现数据驱动的MVVM模式,不刷新控件更新控件

文章展示了C#中实现数据模型接口以及事件处理的方式,包括使用INotifyPropertyChanged接口进行属性更改通知。此外,还演示了依赖注入框架Microsoft.Extensions.DependencyInjection的使用,如何通过服务容器获取对象并订阅事件。
using System;

namespace Test
{
   
   
    public interface IDataModel
    {
   
   
        int Count {
   
    get; set; }

        event EventHandler CountChanged;

    }
}

using System;

namespace Test
{
   
   
    public class DataModel : IDataModel
    {
   
   
        public DataModel()
        {
   
   

        }
        private int count;

        public int Count
        {
   
   
            get {
   
    return count; }
            set {
   
    count = value; OnCountChanged(); }
        }

        public event EventHandler CountChanged;
        /*
         在这个代码中,this表示当前DataModel实例。
        在OnCountChanged()方法中,使用CountChanged?.Invoke(this, EventArgs.Empty)
        来触发CountChanged事件。

        这里的this表示事件的发送者,也就是当前DataModel实例,
        EventArgs.Empty表示事件的参数,这里是一个空的EventArgs实例。
         */
        protected virtual void OnCountChanged()
        {
   
   
            CountChanged?.Invoke(this, EventArgs.Empty);
        }
    }

}

using System.ComponentModel;

namespace Test
{
   
   
    public interface IDataModel2
    {
   
   
        int Count {
   
    get; set; }
        event PropertyChangedEventHandler PropertyChanged;
    }
}

using System.ComponentModel;

namespace Test
{
   
   
    public class DataModel2 : INotifyPropertyChanged, IDataModel2
    {
   
   
        public DataModel2()
        {
   
   

        }
        private int count;

        public int Count
        {
   
   
            get {
   
    return count; }
            set {
   
    count = value; NotifyPropertyChanged("Count"); }
        }

        private void NotifyPropertyChanged(string propertyName)
        {
   
   
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}

using System.ComponentModel;

namespace Test
{
   
   
    public interface IStudent
    {
   
   
        string Name {
   
    get; set; }
        int Age 
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

潘诺西亚的火山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值