WPF: how to override CanExecute method for ApplicationCommands

I use the standard Cut, Copy, and Paste commands (which are part of the ApplicationCommands class). Is it possible to override the CanExecute method?

Here is my code:

XAML:

   <Window.CommandBindings>
        <CommandBinding Command="Copy"
                CanExecute="CopyCanExecute" Executed="CopyExecuted"/>       
    </Window.CommandBindings>

    <StackPanel>
        <TextBox Name="txt"></TextBox>
        <Button Command="Copy" CommandTarget="{Binding ElementName=txt}">copy</Button>
    </StackPanel>

Code for:

private void CopyCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
    e.CanExecute = false;
}

private void CopyExecuted(object sender, ExecutedRoutedEventArgs e)
{
    MessageBox.Show("Copy Executed");
}  

A button still behaves like its command is a standard Copy command.

+3
source share
4 answers

You do this through CommandBinding . A local CommandBinding can indicate a CanExecuteHandler.

For more details and a working example, see this blog post .

+1
source

, , , , CheckBox ..

+1

In the CanExecute handler, you may need to add `e.Handled = true; also so that it doesn’t go and does the standard Copy.CanExecute ()

0
source

Have you tried to bind commands to the text field directly, and not to the window?

0
source

Source: https://habr.com/ru/post/1738803/


All Articles