FocusManager

This example has an interesting detail. The Cut, Copy, and Paste commands are handled by the text box that has focus. However, the command is triggered by the button in the toolbar, which is a completely separate element. In this example, this process works seamlessly because the button is placed in a toolbar, and the ToolBar class includes some built-in magic that dynamically sets the CommandTarget property of its children to the control that currently has focus. (Technically, the ToolBar looks at the parent, which is the window, and finds the most recently focused control in that context, which is the text box. The ToolBar has a separate focus scope, and in that context, the button is focused.)
If you place your buttons in a different container (other than a ToolBar or Menu), you won’t have this benefit. That means your buttons won’t work unless you set the CommandTarget property manually. To do so, you must use a binding expression that names the target element. For example, if the text box is named txtDocument, you would define the buttons like this:

<Button Command="Cut"
CommandTarget="{Binding ElementName=txtDocument}">Cut</Button>
<Button Command="Copy"
CommandTarget="{Binding ElementName=txtDocument}">Copy</Button>
<Button Command="Paste"
CommandTarget="{Binding ElementName=txtDocument}">Paste</Button>

Another, simpler option is to create a new focus scope by using the attached FocusManager.IsFocusScope property. This tells WPF to look for the element in the parent’s focus scope when the command is triggered:

<StackPanel FocusManager.IsFocusScope="True">
<Button Command="Cut">Cut</Button>
<Button Command="Copy">Copy</Button>
<Button Command="Paste">Paste</Button>
</StackPanel>

This approach has the added advantage that the same commands will apply to multiple controls, unlike the previous example where the CommandTarget was hard-coded. Incidentally, the Menu and ToolBar set the FocusManager.IsFocusScope property to true by default, but you can set it to false if you want the simpler command-routing behavior that doesn’t hunt down the focused element in the parent’s context.

댓글

이 블로그의 인기 게시물

Oracle NLS_DATE_FORMAT 변경

Stop console process using Ctrl+C.

Alternative to IValueConvert, QuickConverter