WPF中MVVM手动实现PropertyChanged和RelayCommand

背景:PropertyChanged和Command总是没有记住怎么写

PropertyChanged:

cs 复制代码
public event PropertyChangedEventHandler? PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

-- 使用上特性[CallerMemberName]的作用就是由原本调用这个方法的使用要传入属性的名称作为这个方法的参数,但是现在就不用了,直接调用方法,会自动将参数(这里是属性的名称)传过去。所以调用就直接OnPropertyChanged()就行了,不需要原理的nameof(属性名)

RelayCommand:

cs 复制代码
public class RelayCommand : ICommand
{
    private readonly Action<object> _execute;
    private readonly Predicate<object> _canExecute;

    public RelayCommand(Action<object> execute, Predicate<object> canExecute = null)
    {
        _execute = execute ?? throw new ArgumentNullException(nameof(execute));
        _canExecute = canExecute;
    }

    public bool CanExecute(object parameter)
    {
        return _canExecute == null || _canExecute(parameter);
    }

    public void Execute(object parameter)
    {
        _execute(parameter);
    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }
}
相关推荐
Dem11 分钟前
怎么安装jdk
java·开发语言
wazmlp0018873694 分钟前
python第一次作业
开发语言·python·算法
墨雪不会编程5 分钟前
C++【string篇4】string结尾篇——字符编码表、乱码的来源及深浅拷贝
android·开发语言·c++
Engineer-Jsp11 分钟前
A problem occurred starting process ‘command ‘bash‘‘
开发语言·bash
PnZh0Y118 分钟前
python代码练习1
开发语言·python·算法
sheji341619 分钟前
【开题答辩全过程】以 基于python的图书销售数据可视化系统为例,包含答辩的问题和答案
开发语言·python·信息可视化
_Soy_Milk20 分钟前
【算法工程师】—— Python 高级
开发语言·python·算法
程序猿Code21 分钟前
groovy闭包
开发语言·python
2401_8614121421 分钟前
python 从入门到精通 高清PDF 背记手册
开发语言·python·pdf
lsx20240630 分钟前
jEasyUI 条件设置行背景颜色
开发语言