wpf的mvvm最基础也是最常用的两个东东

一个是属性的绑定

一个是命令的绑定

  1. 属性绑定

    前端页面View中某个依赖属性与ViewModel中的某个变量绑定

    ViewModel要实现INotifyPropertyChanged接口

    可以做一个基类实现此接口,让你的ViewModel继承此基类

public class NotifyBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private void RaisePropertyChange(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public void SetProperty<T>(ref T property, T value, [CallerMemberName]string propertyName = null)
    {
        property = value;
        RaisePropertyChange(propertyName);
    }
}

PropertyChanged事件是实现接口带的

下面两个方法是我们自己写的,为了给子类用

RaisPropertyChange,属性值变化(赋值时)提交属性名,调用PropertyChanged事件

SetProperty方法是属性赋值Setter里执行的

例,一个ViewModel继承NotifyBase

public class TestViewModel : NotifyBase
{
    //定义属性
    private string _content;
    public string Content
    {
        get{ return _content; }
        set{ SetProperty(ref _content, value); }
    }
}

2. 命令绑定

前端以Button的Command绑定为最常见

<Button Command={Binding TestCommand} Content="测试"/>

ViewModel中要添加TestCommand字段,这个字段要实现ICommand接口

做一个类实现ICommand接口,这个类作为TestCommand字段的类型

以下这个是无参的Command基类

public class TCommand : ICommand
{
    private Action _execute;    //执行
    private Func<bool> _canExecute;    //是否可以执行 也可以用Predict, 反正得返回bool类型
    
    public TCommand(Action execute, Func<bool> canExecute)
    {
        _execute = execute;
        _canExecute = canExecute;
    }
    public TCommand(Action execute):this(execute,null)
    {
    }
    //下面这三个是实现接口中的字段和方法
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }
    //返回是否可执行
    //如果是按钮就是按钮是否可用(IsEnabled)
    public bool CanExecute(object parameter)
    {
        if (_canExecute == null) return true;
        return (_execute != null && _canExecute());
    }
    //命令执行的方法
    public void Execute(object parameter)
    {
        _execute?.Invoke();
    }
}

然后在ViewModel中写TestCommand字段

private TCommand _testCommand;
public TCommand TestCommand=>_testCommand??(_testCommand=new TCommand(Test));
private void Test()
{
    //..要执行的代码
}


就是这两个基类:NotifyBase和TCommand就构成了一个最简单的MVVM框架