WPF入门(2)——数据绑定与INotifyPropertyChanged(INPC)

接上篇,我们在MainViewModel类中创建个属性:

public string Name { get; set; }


然后去UI的xaml文件中binding一下:

此时运行程序是不会得到我们想要的结果的,因为还没有设置DataContext。
我们去设置下DataContext:

debug下,按理说UI的button会找到DataContext的Name属性,显示我们的MainViewModel.Name

关于绑定的最好的事情之一是它们使UI与视图模型中的数据保持同步。但是此时我们更改FirstName属性,UI上是不会跟随同步的,因为我们的MainViewModel虽然继承了INotifyPropertyChanged接口但是我们并没有应用。为了实现修改mainViewModel中的属性值后就自动更新到UI上,我们需要应用该接口:

然后,为button创建个事件,当按钮按下后修改MainViewModel的name属性:


debug下试试:

但是,记住每次更改属性值时都会引发事件,这会非常繁琐。由于这种模式非常普遍,因此许多MVVM框架为您的视图模型类提供了一个基类,类似于以下内容:

public abstract class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
 
    protected bool SetProperty<T>(ref T field, T newValue, [CallerMemberName]string propertyName = null)
    {
        if(!EqualityComparer<T>.Default.Equals(field, newValue))
        {
            field = newValue;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            return true;
        }
        return false;
    }
}

这使我们可以像这样重写Name属性:

public class ViewModel : ViewModelBase
{
    private string name;
    public string Name
    {
        get => name;
        set => SetProperty(ref name, value);
    }
}

每次我们更改Name属性时,都会引发INPC事件

工程源代码上传在GitHub上了:https://github.com/feipeng8848/WPF-Demo

参考资料:
https://intellitect.com/getting-started-model-view-viewmodel-mvvm-pattern-using-windows-presentation-framework-wpf/

posted @ 2019-10-08 18:33  feipeng8848  阅读(2478)  评论(0编辑  收藏  举报