Команда CanExecute не меняется - PullRequest
0 голосов
/ 19 июня 2020

Этот пример не имеет смысла, я просто тренируюсь.

У меня есть эта команда:

        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 открывает сообщение box), кроме изменения 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));
            }
        }

1 Ответ

2 голосов
/ 19 июня 2020

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" />
...