命令 CanExecute 不变

Command CanExecute not changing

这个例子应该没​​有意义,我只是在练习。

我有这个命令:

        public class NewCommand : ICommand
        {
            public event EventHandler CanExecuteChanged
            {
                add { CommandManager.RequerySuggested += value; }
                remove { CommandManager.RequerySuggested -= value; }
            }

            public bool CanExecute(object parameter)
            {
                return !((string)parameter == "sample");
            }

            public void Execute(object parameter)
            {
                MessageBox.Show("The New command was invoked");
            }
        }

效果很好(按 Button 打开消息框),除了在 TextBox 中更改 string 什么都不做。当 Button 应该被阻止时,它不是。

这是我的 XAML 和 ViewModel:

    <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
        <TextBox Text="{Binding TextB}"></TextBox>
        <Button Command="{Binding Path=NewCommand}" FontSize="128">New</Button>
    </StackPanel>
public class ViewModel : INotifyPropertyChanged
        {
            private string _textB;
            public ICommand NewCommand { get; set; }
            public string TextB
            {
                get => _textB;
                set
                {
                    if (_textB == value) return;
                    _textB = value;
                    OnPropertyChanged(nameof(TextB));
                }
            }

            public event PropertyChangedEventHandler PropertyChanged;

            public void OnPropertyChanged(string memberName)
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(memberName));
            }
        }

CanExecute 始终 return 为真,因为 parameter 为空,并且不匹配 "sample"。绑定命令参数:

<TextBox Text="{Binding TextB}"/>
<Button Command="{Binding Path=NewCommand, UpdateSourceTrigger=PropertyChanged}"
        CommandParameter="{Binding Path=TextB}"  
        FontSize="128" Content="New" />