How to use the CanExecute Method from ICommand on WPF

后端 未结 1 556
独厮守ぢ
独厮守ぢ 2020-12-17 22:21

How does one use the CanExecute Method from the ICommand interface?


In my example i have a SaveCommand which i only what to be enable

1条回答
  •  星月不相逢
    2020-12-17 22:27

    Instead of defining your own implementation of ICommand, use a RelayCommand.

    In the below sample code, the save Button is enabled when the user types something in the TextBox.

    XAML:

    
        
            
            

    Code behind:

    using System;
    using System.Windows;
    using System.Windows.Input;
    
    namespace RelayCommandDemo
    {
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
    
                DataContext = new VM();
            }
        }
        public class VM
        {
            public String Name { get; set; }
    
            private ICommand _SaveCommand;
    
            public ICommand SaveCommand
            {
                get { return _SaveCommand; }
            }
    
            public VM()
            {
                _SaveCommand = new RelayCommand(SaveCommand_Execute, SaveCommand_CanExecute);
            }
    
            public void SaveCommand_Execute()
            {
                MessageBox.Show("Save Called");
            }
    
            public bool SaveCommand_CanExecute()
            {
                if (string.IsNullOrEmpty(Name))
                    return false;
                else
                    return true;
            }
        }
    
        public class RelayCommand : ICommand
        {
            public event EventHandler CanExecuteChanged
            {
                add { CommandManager.RequerySuggested += value; }
                remove { CommandManager.RequerySuggested -= value; }
            }
            private Action methodToExecute;
            private Func canExecuteEvaluator;
            public RelayCommand(Action methodToExecute, Func canExecuteEvaluator)
            {
                this.methodToExecute = methodToExecute;
                this.canExecuteEvaluator = canExecuteEvaluator;
            }
            public RelayCommand(Action methodToExecute)
                : this(methodToExecute, null)
            {
            }
            public bool CanExecute(object parameter)
            {
                if (this.canExecuteEvaluator == null)
                {
                    return true;
                }
                else
                {
                    bool result = this.canExecuteEvaluator.Invoke();
                    return result;
                }
            }
            public void Execute(object parameter)
            {
                this.methodToExecute.Invoke();
            }
        }
    }
    

    0 讨论(0)
提交回复
热议问题