WPF 数据绑定:数据源Source-目标Target

数据源Source-目标Target

数据源实现INotifyPropertyChanged接口,实现“通知”
目标实现依赖属性

举例

后台的数据源,实现INotifyPropertyChanged接口,实现“通知”

public class Student : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private string _name;
    public string Name
    {
        get
        {
            return _name;
        }
        set
        {
            _name = value;
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name"));
            }
        }
    }
}

数据源赋值DataContext

public BindDemo()
{
    InitializeComponent();
    Student student = new Student()
    {
        Name = "Lulu"
    };
    DataContext = student;
}

前端的Label绑定Name属性,其中Label是实现了依赖属性的
Tips:WPF的所有现成控件都是实现了依赖属性的

<Label Content="{Binding Name}"></Label>

示例代码

https://github.com/zLulus/NotePractice/tree/dev3/WPF/WpfDemo/Bind 下的BindDemoForINotifyPropertyChanged

原文地址:https://www.cnblogs.com/Lulus/p/8145688.html