Reputation: 106549
Consider the following example with a menu and a button:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<DockPanel>
<Menu DockPanel.Dock="Top">
<MenuItem Header="Paste" Command="ApplicationCommands.Paste" />
</Menu>
<Button Command="ApplicationCommands.Paste">Paste</Button>
<TextBox>Content</TextBox>
<TextBox>Content2</TextBox>
</DockPanel>
</Window>
When I put keyboard focus in one of the text boxes, the TextBox declares that it can handle ApplicationCommands.Paste
, and so I expect the button and the menu item to enable themselves. What I get instead is that the menu item enables itself, and the button does not. (The button doesn't appear to be "listening" to the TextBox
' CommandBinding
)
What's going on here, and is there any way I can work around this?
EDIT: I did find this question --> WPF routed command enabling works with menu but not with a button <-- but this is not suitable in this case. The button should not be keyboard focusable, and setting it as a focus scope makes it focusable. I can't bind the source, because the actual source needs to be controlled by keyboard focus.
Upvotes: 2
Views: 160
Reputation: 407
It appears that you can't use the Command property of a button in this manner unless it's contained in a Toolbar. I get the same results you do with your xaml, but I use the same code regularly to assign this command to a button in a toolbar.
See Copy and paste commands with WPF buttons for more information.
EDIT:
You're right. It has to do with the FocusScope, and there are two ways to fix it, as shown here:
WPF routed command enabling works with menu but not with a button
You can set FocusManager.IsFocusScope
on the button:
<Button Command="ApplicationCommands.Paste" FocusManager.IsFocusScope="True">Paste</Button>
Alternately, you can set the button's command target, but this will only work for one textbox.
Upvotes: 1