INotifyPropertyChanged

发布时间 2023-11-06 15:23:25作者: 时而有风

  可以将TextBox控件(其他控件也基本一样)与某个变量进行绑定,做出改变变量则控件也跟着改变的效果。

  首先需要声明一个类,该类用来与控件绑定:

using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace TestWPF
{
    public class Person : INotifyPropertyChanged
    {
        private string _Name;

        public string Name
        {
            get => _Name; //等同于return _Name;
            set
            {
                _Name = value;
                //执行通知属性已经发生改变
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Name"));
            }
        }

        #region resharper补全代码

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        protected bool SetField<T>(ref T field, T value, [CallerMemberName]string propertyName = null)
        {
            if (EqualityComparer<T>.Default.Equals(field, value))
            {
                return false;
            }

            field = value;
            OnPropertyChanged(propertyName);
            return true;
        }

        #endregion
    }
}

  然后在XAML文件中绑定:

<TextBox Name="textBox1" Width="400" Height="200" Text="{Binding Name}" />//Name为要绑定的变量

  其中,继承的INotifyPropertyChanged类是用来发送消息告诉控件变量的值改变了,控件需要作出调整。 

  接着实例化相应的对象,并跟控件绑定:

public partial class MainWindow : Window
{
    public Person person = new Person();

    public MainWindow()
    {
        //初始化
        InitializeComponent();
        person.Name          = "1313";//初始赋值
        textBox1.DataContext = person;
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        person.Name = textbox2.Text;
    }
}

  

  点击按钮修改变量Name的值后,textBox的文本随之改变: