2

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>

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Shane
  • 2,271
  • 3
  • 27
  • 55

1 Answers1

2

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!

RichardOD
  • 28,883
  • 9
  • 61
  • 81
  • Thanks very much – very enlightening. I am starting see why the button is treated differently. One thing I noticed is without FocusManager.IsFocusScope="True" the button takes the focus away from the text box whereas the menu does not. When the property is applied the button behaves like the menu. I guess this make sense when you think about it – the command is meant to be enabled when a control that can accept it has the focus. However, the more I use WPF the more it seems like black magic. – Shane May 21 '12 at 11:23
  • Typically you'd put the property on a panel- for example a StackPanel containing the button. If it helps there is quite a lot on this in the book Pro WPF in C# 2010 in the commands chapter (chapter 9). – RichardOD May 21 '12 at 11:29