C#實現某一屬性值變化時觸發事件


在我們做工業軟件中,經常會遇到要實時監控某一點,在這個點變化時去做一些事情

放入程序里呢,就是要實時監控某一屬性的值,當值發生變化時觸發事件,其核心就是借助屬性的Set方法,來判斷當前set的值是否與原來的值相等,如果相等直接賦值不予理會,如果不相等,說明值變了,根據自己調用的方法,聲明委托,事件,觸發方法

核心代碼:

public delegate void tempChange(object sender,EventArgs e);
public event tempChange onTempChange;

private string _temp;
public string Temp
{
            get { return _temp; }
            set
            {
                if (_temp!=value &&_temp !=null)
                {
                    onTempChange(new object(), new EventArgs());
                }
                _temp= value; 
       }
}

下邊我們做一個Demo ,來測試一下

我們新建一個from,上邊添加一個lable,添加一個button 我們通過button來改變這個temp屬性的值 ,使之觸發對應的事件

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        int i = 0;
        private void Form1_Load(object sender, EventArgs e)
        {
            changeEvent += Form1_changeEvent;
        }

        void Form1_changeEvent(string value)
        {
            this.richTextBox1.Invoke(new Action(() => { this.richTextBox1.AppendText("當前lable的值為" + value+"\r\n"); }));
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Temp = i + "";
            label1.Text = Temp;
            i++;
        }

        public delegate void ChangeDelegate(string value);
        public event ChangeDelegate changeEvent;

        public string _temp;
        public string Temp
        {
            get { return _temp; }
            set
            {
                if (_temp != value)
                {
                    changeEvent(value);
                }
                _temp = value;
            }
        }
    }
}

測試:

可以看到 我們每點擊一次按鈕 都改變了temp的值,從而觸發了changeEvent事件 ------給richTextBox添加文本

===================================================================================================

分割線

===================================================================================================

鄭重聲明:感謝id為 特別 的前輩提醒

其實微軟給我們提供了INotifyPropertyChanged接口用於通知客戶端,通常綁定客戶端,在屬性值已更改。

 

微軟提供了如何:實現 INotifyPropertyChanged 接口 的文檔,各位看官如有興趣可以先去看一下官方的文檔,畢竟我寫的肯定簡陋

 

接下來我根據文檔自己寫一個Demo測試一下

還是和上邊一樣我們新建一個from,上邊添加一個lable,添加一個button 我們通過button來改變這個temp屬性的值 ,使之觸發對應的事件

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication3
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        Demo demo = new Demo();
        private void Form2_Load(object sender, EventArgs e)
        {
            
            //給changed事件注冊方法
            demo.PropertyChanged += demo_PropertyChanged;
        }
        void demo_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            SetMsg(e.PropertyName);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //通過點擊事件,將當前時間的值賦給Temp 從而觸發屬性改變事件
            demo.Temp = DateTime.Now.ToString();
        }
        
        private void SetMsg(string msg)
        {
            //向richTextBox中添加文本
            this.richTextBox1.Invoke(new Action(() => {this.richTextBox1.AppendText(msg+"\r\n"); }));
        }
    }
    public class Demo : INotifyPropertyChanged
    {
        //實現INotifyPropertyChanged 
        public event PropertyChangedEventHandler PropertyChanged;

        //此方法由每個屬性的Set訪問者調用。
        //應用於可選propertyName的CallerMemberName屬性
        //參數導致調用者的屬性名稱被替換為參數。
        private void PropChanged([CallerMemberName] String propertyName = "")
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        //定義屬性
        private string _temp;

        public string Temp
        {

            get { return _temp; }
            set
            {
                if (this._temp != value)
                {
                    PropChanged(value);
                    this._temp = value;
                }

            }
        }
    }

}

測試結果:

測試完成

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM