Why is a button enabled if the Command binding resolves to null?

前端 未结 3 1698
别跟我提以往
别跟我提以往 2021-01-19 06:43

OK, the XAML is quite simple and uses MVVM to bind to an ICommand SomeCommand { get; } property on a view model:

3条回答
  •  醉话见心
    2021-01-19 07:12

    My colleague found an elegant solution: using a binding fallback value!

    public class NullCommand : ICommand
    {
        private static readonly Lazy _instance = new Lazy(() => new NullCommand());
    
        private NullCommand()
        {
        }
    
        public event EventHandler CanExecuteChanged;
    
        public static ICommand Instance
        {
            get { return _instance.Value; }
        }
    
        public void Execute(object parameter)
        {
            throw new InvalidOperationException("NullCommand cannot be executed");
        }
    
        public bool CanExecute(object parameter)
        {
            return false;
        }
    }
    

    And then the XAML looks like:

    
    

    The advantage of this solution is that it works better if you break Law of Demeter and you have some dots in the binding path, where each instance might become null.

提交回复
热议问题