我必须使用CommandTarget吗?我认为任何有针对性的元素都会收到命令

lud*_*det 4 wpf xaml routed-commands

我正在尝试了解如何使用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>
Run Code Online (Sandbox Code Playgroud)

如果我将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>
Run Code Online (Sandbox Code Playgroud)

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

谢谢!

小智 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"/>
Run Code Online (Sandbox Code Playgroud)

根据http://msdn.microsoft.com/en-us/magazine/cc785480.aspx,原因是:

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

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