WPF-Prism CanExecute method not being called

前端 未结 4 1336
南方客
南方客 2021-02-01 19:06

I am coding a simple login UserControl with two TextBoxes (Username and Password) and a Login button. I want the Login button to be enabled only when the username and password f

相关标签:
4条回答
  • 2021-02-01 19:36

    Starting with Prism6 the DelegateCommand can "observe" your propertys. Means everytime your property is changing the CanExecute-Method is called. The good thing is you get rid of RaiseCanExecuteChanged in the Propertysetter. You can also chain-call that method if you want to observe more properties:

    public LoginViewModel()
    {
        this.LoginCommand =
            new DelegateCommand<object>(
                this.LoginExecute, this.CanLoginExecute).ObservesProperty(() => Username).ObservesProperty(() => Password);
    }
    

    Furthermore if you just want your DelegateCommand be called depending on the state of a boolean property you can use .ObservesCanExecute(()=> BoolProp)

    public LoginViewModel()
    {
        this.LoginCommand =
            new DelegateCommand<object>(
                this.LoginExecute).ObservesCanExecute(()=> IsServerOnline).ObservesProperty(() => Username).ObservesProperty(() => Password);
    }
    

    You dont need this.CanLoginExecute anymore.

    0 讨论(0)
  • 2021-02-01 19:39

    Code for RaiseCanExecuteChanged:

        private void RaiseCanExecuteChanged()
        {
            DelegateCommand<object> command = LoginCommand as DelegateCommand<object>;
            command.RaiseCanExecuteChanged();
        }
    
        public const string UsernameProperty = "Username";
        private String _username;
        public String Username
        {
            get { return _username; }
            set
            {
                _username = value;
                this.NotifyPropertyChanged(UsernameProperty);
                RaiseCanExecuteChanged();
            }
        }
    
    0 讨论(0)
  • 2021-02-01 19:46

    It is most likely that the bound control is never asking for the CanExecute state again. You need to call the RaiseCanExecuteChanged method on the DelegateCommand whenever you detect a condition that changes the command's CanExecute state. This signals the bound control to update the CanExecute state.

    0 讨论(0)
  • 2021-02-01 19:55

    Here's a little workaround for Prism (tested with Prism.Core 7.1.0.431):

    public class RelayCommand : DelegateCommand
    {
        public RelayCommand(Action executeMethode) : base(executeMethode)
        {
    
        }
    
        public RelayCommand(Action executeMethode, Func<bool> canExecuteMethode) : base(executeMethode, canExecuteMethode)
        {
    
        }
    
        public override event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
    }
    
    0 讨论(0)
提交回复
热议问题