开发者

WPF: How to redefine CanExecute method of ApplicationCommands

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜