相关文章推荐
豪爽的烈马  ·  Spark ...·  11 月前    · 
狂野的卤蛋  ·  Selenium - Running ...·  1 年前    · 
文质彬彬的自行车  ·  python - Flask: ...·  1 年前    · 
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 ; }

在ViewModel中创建一个属性,来表示按钮是否启用:

private bool _isButtonEnabled;
public bool IsButtonEnabled
    get { return _isButtonEnabled; }
        _isButtonEnabled = value;
        OnPropertyChanged(nameof(IsButtonEnabled));

在ViewModel中创建一个RelayCommand实例,并使用IsButtonEnabled属性作为CanExecute参数:

public RelayCommand ButtonCommand { get; set; }
public ViewModel()
    ButtonCommand = new RelayCommand(OnButtonCommandExecute, OnButtonCommandCanExecute);
private bool OnButtonCommandCanExecute(object parameter)
    return IsButtonEnabled;
private void OnButtonCommandExecute(object parameter)
    //执行按钮命令

在XAML中,绑定按钮的IsEnabled属性到ViewModel的IsButtonEnabled属性,并绑定按钮的Command属性到ButtonCommand命令:

<Button Content="Click me!" IsEnabled="{Binding IsButtonEnabled}" Command="{Binding ButtonCommand}"/>

这样,在ViewModel中修改IsButtonEnabled属性的值时,按钮的启用/禁用状态就会发生变化,从而实现了按钮状态的控制。

  •