tags:

views:

207

answers:

2

I use standard Cut, Copy and Paste commands (which is part of ApplicationCommands class). Is it possible to redefine 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-behind:

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

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

The button still behave like its command is standard Copy command.

+1  A: 

You do this via a CommandBinding. The local CommandBinding can specify a CanExecuteHandler.

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

Reed Copsey
Can't uderstand why it doesn't work with Copy\Cut\Paste (example with Help command works fine). I add CommandBinding to Copy and define CanExecute to return false: e.CanExecute = false in code-behind file. But Copy still works like standard Copy command: when I select a text in TextBox the button becomes enabled. Could you help me to understand this issue?
Nike
Show your code, and we might be able to help...
Reed Copsey
I add my code to the question
Nike
A: 

In the CanExecute handler you might need to add `e.Handled = true; also, so that it doesnt go and execute the standard Copy.CanExecute()

Jobi Joy
e.Handled = true has no effect on this. I also changed e.CanExecute = true, but Click on Button just copied selected text and my MessageBox doesn't appreared
Nike