问题
In the following example the menu is enabled when the text receives the focus but not the button. I have tried it with just the button and the text box but the behaviour is the same.
<Window x:Class="WpfPopup.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 Command="ApplicationCommands.Paste" />
</Menu>
<TextBox BorderBrush="Black" BorderThickness="2" Margin="25" TextWrapping="Wrap" x:Name="text1" Height="58" Width="203" >
The MenuItem will not be enabled until
this TextBox gets keyboard focus
</TextBox>
<Button Content="Button" Height="23" Name="button1" Width="93" Command="ApplicationCommands.Paste" />
</DockPanel>
回答1:
There are two simple ways to fix this:
1) Use FocusManager.IsFocusScope:
<Button Content="Button" Height="23" Name="button1" Width="93" Command="ApplicationCommands.Paste" FocusManager.IsFocusScope="True"/>
2) Set the CommandTarget on the button manually:
<Button Content="Button" Height="23" Name="button1" Width="93" Command="ApplicationCommands.Paste" CommandTarget="{Binding ElementName=text1}" />
You are probably wondering why this works for the menu item? If you read the documentation for FocusManager.IsFocusScope attached property you will get the answer:
By default, the Window class is a focus scope as are the Menu, ContextMenu, and ToolBar classes. An element which is a focus scope has IsFocusScope set to true.
Very confusing when you don't know that!
来源:https://stackoverflow.com/questions/10683574/wpf-routed-command-enabling-works-with-menu-but-not-with-a-button