4

我试图了解如何使用 RoutedCommands。我的印象是,如果我没有在 Button 上指定 CommandTarget,任何有焦点的元素都会收到命令。但由于某种原因,它不起作用。这是不起作用的xaml:

<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 它可以工作,但仅限于指定的文本框。

<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>

如何让任何聚焦元素接收命令?

谢谢!

4

1 回答 1

8

您必须设置FocusManager.IsFocusScopeTrue

<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/en-us/magazine/cc785480.aspx,原因是这样的:

如果IsFocusScope="False",命令调用程序在它自己在可视树中的位置和可视树的根之间查找命令绑定。

如果IsFocusScope="True",命令调用程序还沿着从根到焦点元素的可视树路径查找命令绑定。

于 2012-05-31T13:11:42.987 回答