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)); } }

浙公网安备 33010602011771号