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; }
    }
}
相关推荐
视图猿人16 分钟前
RxJS基本使用及在next.js中使用的例子
开发语言·javascript
墨雪不会编程20 分钟前
C++的基础语法篇一 ——命名空间
开发语言·c++
墨客希36 分钟前
安装 awscli
开发语言
天天进步20151 小时前
Python全栈项目:结合Puppeteer和AI模型操作浏览器
开发语言·人工智能·python
唐僧洗头爱飘柔95271 小时前
【GORM(3)】Go的跨时代ORM框架!—— 数据库连接、配置参数;本文从0开始教会如何配置GORM的数据库
开发语言·数据库·后端·golang·gorm·orm框架·dsn
Jonathan Star1 小时前
在 Go 语言中,模板字符串
开发语言·后端·golang
闲人编程1 小时前
用Python识别图片中的文字(Tesseract OCR)
开发语言·python·ocr·识图·codecapsule
程序员卷卷狗1 小时前
JVM 内存结构与 GC 调优全景图
java·开发语言·jvm
froginwe111 小时前
HTML 段落
开发语言
z20348315202 小时前
我与C++的故事
开发语言·c++·c++40周年