INotifyPropertyChanged的作用

来源:http://www.cnblogs.com/hryan/archive/2017/12/02/7954107.html
-Advertisement-
Play Games

最近學習數據驅動UI,瞭解到INotifyPropertyChanged這個介面的用法,看了很多網上的文章,自己作了一個總結。 INotifyPropertyChanged這個介面其實非常簡單,只有一個PropertyChanged事件,如果類繼承了這個介面,就必須實現介面。用VS的提示,就是補充了 ...


最近學習數據驅動UI,瞭解到INotifyPropertyChanged這個介面的用法,看了很多網上的文章,自己作了一個總結。

INotifyPropertyChanged這個介面其實非常簡單,只有一個PropertyChanged事件,如果類繼承了這個介面,就必須實現介面。用VS的提示,就是補充了一句話:

public event PropertyChangedEventHandler PropertyChanged;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace Demo001
{
    class Student:INotifyPropertyChanged
    {
        private string name;
        private int age;
        public string Name
        {
            get { return name; }
            set
            {
                if (this.name == value) { return; }
                this.name = value;
                Notify("Name");
            }
        }
        public int Age
        {
            get { return age; }
            set
            {
                if (this.age == value) { return; }
                this.age = value;
                Notify("Age");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void Notify(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }

        }

    }
}

剩下的就是對事件PropertyChanged的操作,於是我想可不可以直接定義這個事件而不繼承介面INotifyPropertyChanged,結果發現也是可以的。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace Demo001
{
    class Student
    {
        private string name;
        private int age;
        public string Name
        {
            get { return name; }
            set
            {
                if (this.name == value) { return; }
                this.name = value;
                Notify("Name");
            }
        }
        public int Age
        {
            get { return age; }
            set
            {
                if (this.age == value) { return; }
                this.age = value;
                Notify("Age");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void Notify(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }

        }

    }
}

只不過這時候的PropertyChanged是自定義的事件了,我們可以隨意改變這個名字,比如pChanged,但是繼承INotifyPropertyChanged介面後,只能用PropertyChanged這個名字。

在Form中註冊事件,附代碼:

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

namespace Demo001
{
    public partial class Form1 : Form
    {
        Student stu = new Student();
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            stu.PropertyChanged += changed;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            stu.Name = textBox1.Text;
            stu.Age = int.Parse(textBox2.Text);
        }

        public void changed(object sender, PropertyChangedEventArgs e)
        {
            switch(e.PropertyName)
            {
                case "Name":
                    Console.WriteLine("Name Changed");
                    break;
                case "Age":
                    Console.WriteLine("Age Changed");
                    break;
            }
        }

    }
}
namespace Demo001
{
    partial class Form1
    {
        /// <summary>
        /// 必需的設計器變數。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的資源。
        /// </summary>
        /// <param name="disposing">如果應釋放托管資源,為 true;否則為 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗體設計器生成的代碼

        /// <summary>
        /// 設計器支持所需的方法 - 不要修改
        /// 使用代碼編輯器修改此方法的內容。
        /// </summary>
        private void InitializeComponent()
        {
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.textBox2 = new System.Windows.Forms.TextBox();
            this.button1 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(59, 33);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(100, 21);
            this.textBox1.TabIndex = 0;
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(12, 38);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(29, 12);
            this.label1.TabIndex = 1;
            this.label1.Text = "姓名";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(12, 80);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(29, 12);
            this.label2.TabIndex = 3;
            this.label2.Text = "年齡";
            // 
            // textBox2
            // 
            this.textBox2.Location = new System.Drawing.Point(59, 75);
            this.textBox2.Name = "textBox2";
            this.textBox2.Size = new System.Drawing.Size(100, 21);
            this.textBox2.TabIndex = 2;
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(59, 129);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 4;
            this.button1.Text = "設定";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(195, 182);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.textBox2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.textBox1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.TextBox textBox2;
        private System.Windows.Forms.Button button1;
    }
}

 

備忘:委托是特殊的類,事件是一種委托,所以事件註冊,應該是“附加”方法,而不是“等於”方法。

委托將參數傳給相應的方法,一個作用是(子窗體)傳遞參數,另一個作用是(主窗體)調用方法。

委托傳遞參數,可以用於窗體傳值,主視窗利用子窗體構造函數傳值給子窗體,子窗體將值傳給委托(=子窗體傳值給主窗體的方法,從而傳值給主窗體)。

委托調用方法,主窗體註冊方法,子窗體定義委托(事件),在子窗體給委托傳值的時候觸發主窗體調用方法,從而改變主窗體的一些UI變化。

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 在裸板2440中,當我們使用nand啟動時,2440會自動將前4k位元組複製到內部sram中,如下圖所示: 然而此時的SDRAM、nandflash的控制時序等都還沒初始化,所以我們就只能使用前0~4095地址,在前4k地址里來初始化SDRAM,nandflash,初始化完成後,才能將nandflas ...
  • 突然發現VS2017.15.4.5 打開項目特別慢,並且生成項目時也要等上好久好久, 一直以為是vs更新的問題,輾轉半天發現是項目本身原因。 dotnet core 項目下如果出現一個文件夾內包含大量的文件,比如node_modules之類的,會影響dotnet run的運行效率, 解決辦法: cs ...
  • http://www.cnblogs.com/edison1105/archive/2012/07/30/2616082.html 1、首先看一個簡單的例子 大家都知道要實現foreach的必須要實現IEnumerable和IEnumerator的介面,只有實現了它們,才能實現遍歷,所以要講fore ...
  • 在nuget中下載ServiceStack.Redis,但是運行之後會出現一個問題: Exception: “Com.JinYiWei.Cache.RedisHelper”的類型初始值設定項引發異常。System.TypeInitializationException: “Com.JinYiWei. ...
  • data.xml 通過 linq to xml ,查找價格超過10的產品,並列印供應商名稱與產品名稱; 輸出 SupplierName=CD-by-CD-by-Sondheim , ProductName=AssassinsSupplierName=Solely Sondheim , Product ...
  • 瞭解一個語言最好的方式就是在編輯器中按照語法規則輸入代碼,然後運行並查看結果是否符合預期。本博文介紹S#編輯器軟體界面及其相關各模塊的主要功能,並通過通過帶有局部變數的S#代碼來表達和生成幾何圖形,從而說明瞭S#代碼的常用編寫流程。 ...
  • 瞭解一個語言最好的方式就是在編輯器中按照語法規則輸入代碼,然後運行並查看結果是否符合預期。本博文內容非常重要,承上啟下,不但公開了S#語言的所有武功招式——語法規則,並提供了練功的基礎工具——編輯器,統統都是乾貨呀。 ...
  • 在C#的字元串,其中有許多空格,現要求是把多餘的空格去除保留一個。原理是使用Split()方法進行分割,分割有一個選項是RemoveEmptyEntries,然後再把分割後的字元串Join起來。 string string1 = "AAaaA Oopps 32 211 44.8 69 15.9 C# ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...