WPFMVVM实现ICommand与INotifyPropertyChanged接口

话不多说直接上代码

 

带参数 ICommand实现代码

 

复制代码
 private readonly Action<T> _execute;
 private readonly Func<T, bool> _canExecute;

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

 public bool CanExecute(object parameter) => _canExecute == null || _canExecute((T)parameter);

 public void Execute(object parameter) => _execute((T)parameter);

 public event EventHandler CanExecuteChanged
 {
     add => CommandManager.RequerySuggested += value;
     remove => CommandManager.RequerySuggested -= value;
 }
复制代码

 

不带参数 ICommand实现代码

复制代码
public class Command : ICommand
{
public event EventHandler? CanExecuteChanged;

public bool CanExecute(object? parameter) => true;

public void Execute(object? parameter)
{
if (parameter is RoutedEventArgs e)
{ e.Handled = true; // 阻止事件传播
}
DoExecute
?.Invoke(parameter); } public Action<object> DoExecute { get; set; } public Command(Action<object> doExecute) { DoExecute = doExecute; } }
复制代码

INotifyPropertyChanged实现代码

 

复制代码
internal class NotifyBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged

public event EventHandler? CanExecuteChanged
{
add
{
CommandManager.RequerySuggested += value;
}


remove
{
CommandManager.RequerySuggested -= value;
}
}

public void SetProperty<T>(ref T feild, T value, [CallerMemberName] string propName = "")
{
feild = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
}

}
复制代码
posted @   ¥东方不败  阅读(52)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示