命令可以执行不变

这个例子是没有道理的,我只是在练习。

我有以下命令:

        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打开消息框),除了在string中更改TextBox不会执行任何操作。当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));
            }
        }
iCMS 回答:命令可以执行不变

CanExecute始终返回true,因为parameter为null,并且与"sample"不匹配。绑定CommandParameter:

<TextBox Text="{Binding TextB}"/>
<Button Command="{Binding Path=NewCommand,UpdateSourceTrigger=PropertyChanged}"
        CommandParameter="{Binding Path=TextB}"  
        FontSize="128" Content="New" />
本文链接:https://www.f2er.com/2098269.html

大家都在问