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; }
    }
}
相关推荐
LyaJpunov12 分钟前
C++中move和forword的区别
开发语言·c++
程序猿练习生17 分钟前
C++速通LeetCode中等第9题-合并区间
开发语言·c++·leetcode
一名路过的小码农27 分钟前
C/C++动态库函数导出 windows
c语言·开发语言·c++
m0_6312704029 分钟前
标准c语言(一)
c语言·开发语言·算法
万河归海42830 分钟前
C语言——二分法搜索数组中特定元素并返回下标
c语言·开发语言·数据结构·经验分享·笔记·算法·visualstudio
Messiah___35 分钟前
【论文阅读】Slim Fly: A Cost Effective Low-Diameter Network Topology 一种经济高效的小直径网络拓扑
开发语言·php
充值内卷44 分钟前
WPF入门教学四 WPF控件概述
windows·ui·wpf
农民小飞侠1 小时前
python AutoGen接入开源模型xLAM-7b-fc-r,测试function calling的功能
开发语言·python
指尖流烟1 小时前
C#调用图表的使用方法
开发语言·c#
敲代码不忘补水1 小时前
Python 项目实践:简单的计算器
开发语言·python·json·项目实践