我必须使用CommandTarget吗?我以为任何专注的元素都会收到命令 [英] Do I have to use CommandTarget? I thought any focused element would receive the Command
问题描述
我试图了解如何使用RoutedCommands.我的印象是,如果我没有在Button上指定CommandTarget,则任何聚焦的元素都将接收该命令. 但是由于某种原因,它不起作用.这是不起作用的xaml:
I'm trying to understand how to use RoutedCommands. I was under the impression that if I don't specify a CommandTarget on the Button, any focused element will receive the command. But for some reason it doesn't work. Here is the xaml that doesn't work:
<Window x:Class="WpfTest11_Commands2.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">
<Grid>
<TextBox Height="177" HorizontalAlignment="Left"
Margin="12,12,0,0" Name="textBox1" VerticalAlignment="Top" Width="233" AcceptsReturn="True" />
<TextBox Height="177" HorizontalAlignment="Left"
Margin="258,12,0,0" Name="textBox2" VerticalAlignment="Top" Width="233" AcceptsReturn="True" />
<Button Content="Cut"
Height="23" HorizontalAlignment="Left" Margin="12,195,0,0" Name="button1" VerticalAlignment="Top" Width="75"
Command="ApplicationCommands.Cut"/>
</Grid>
</Window>
如果我将CommandTarget添加到Button中,它将起作用,但仅适用于当然指定的文本框.
If I add CommandTarget to the Button it works, but only for the textbox that is specified of course.
<Window x:Class="WpfTest11_Commands2.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">
<Grid>
<TextBox Height="177" HorizontalAlignment="Left" Margin="12,12,0,0" Name="textBox1" VerticalAlignment="Top" Width="233" AcceptsReturn="True" />
<TextBox Height="177" HorizontalAlignment="Left" Margin="258,12,0,0" Name="textBox2" VerticalAlignment="Top" Width="233" AcceptsReturn="True" />
<Button Content="Cut"
Height="23" HorizontalAlignment="Left" Margin="12,195,0,0" Name="button1" VerticalAlignment="Top" Width="75"
Command="ApplicationCommands.Cut"
CommandTarget="{Binding ElementName=textBox1}"/>
</Grid>
</Window>
如何使任何有重点的元素接收命令?
How can I make any focused element receive the command?
谢谢!
推荐答案
您必须将FocusManager.IsFocusScope
设置为True
.
<Button Content="Cut" FocusManager.IsFocusScope="True"
Margin="12,195,0,0"
Height="23" HorizontalAlignment="Left" Name="button1" VerticalAlignment="Top" Width="75"
Command="ApplicationCommands.Cut"/>
根据 http://msdn.microsoft.com/zh-CN/magazine/cc785480.aspx ,原因是这样的:
如果为IsFocusScope="False"
,则命令调用程序在其在视觉树中的自身位置与视觉树的根之间查找命令绑定.
If IsFocusScope="False"
, the command invoker looks for a command binding between its own location in the visual tree and the root of the visual tree.
如果为IsFocusScope="True"
,则命令调用程序还将沿着从根到焦点元素的可视树路径进行查找,以进行命令绑定.
If IsFocusScope="True"
, the command invoker also looks along the visual tree path from the root to the focus element for a command binding.
这篇关于我必须使用CommandTarget吗?我以为任何专注的元素都会收到命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!