开发者

WPF: How to redefine CanExecute method of ApplicationCommands

开发者 https://www.devze.com 2022-12-24 03:54 出处:网络
I use standard Cut, Copy and Paste commands (which is part of ApplicationCommands class). Is it possible to redefine CanExecute method?

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 beha开发者_StackOverflow中文版ve like its command is standard Copy command.


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

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


The copy command will not work when the focus is on a textbox where the commands have already been handled, but it will work on elements like CheckBox etc.


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


You can set the commandbinding to the textbox directly instead of to the window.

0

精彩评论

暂无评论...
验证码 换一张
取 消