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; }
    }
}
相关推荐
fish_xk1 小时前
c++中的引用和数组
开发语言·c++
酒尘&4 小时前
JS数组不止Array!索引集合类全面解析
开发语言·前端·javascript·学习·js
冬夜戏雪4 小时前
【java学习日记】【2025.12.7】【7/60】
java·开发语言·学习
Macbethad4 小时前
工业设备数据记录程序技术方案
wpf·信息与通信
xwill*4 小时前
分词器(Tokenizer)-sentencepiece(把训练语料中的字符自动组合成一个最优的子词(subword)集合。)
开发语言·pytorch·python
咖啡の猫5 小时前
Python列表的查询操作
开发语言·python
quikai19815 小时前
python练习第三组
开发语言·python
JIngJaneIL6 小时前
基于Java非遗传承文化管理系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot
吃西瓜的年年6 小时前
1. 初识C语言
c语言·开发语言
CHANG_THE_WORLD6 小时前
Python 字符串全面解析
开发语言·python