简体   繁体   English

命令 CanExecute 不变

[英]Command CanExecute not changing

This example isn't supposed to make sense, i'm just practicing.这个例子不应该有意义,我只是在练习。

I have this command:我有这个命令:

        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");
            }
        }

and it works great (pressing Button opens message box), except changing string in TextBox does nothing.它工作得很好(按下Button打开消息框),除了在TextBox中更改string什么都不做。 When Button should be blocked, it isn't.Button应该被阻止时,它不是。

This is my XAML and ViewModel:这是我的 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 always return true, because parameter is null, and doesn't match "sample" . CanExecute 总是返回 true,因为parameter是 null,并且与"sample"不匹配。 Bind CommandParameter:绑定命令参数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM