4

RoutedCommandsの使用方法を理解しようとしています。ボタンで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をボタンに追加すると機能しますが、もちろん指定されているテキストボックスに対してのみ機能します。

<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.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/en-us/magazine/cc785480.aspxによると、その理由は次のとおりです。

の場合IsFocusScope="False"、コマンド呼び出し元は、ビジュアル ツリー内の自身の場所とビジュアル ツリーのルートとの間でコマンド バインディングを探します。

の場合IsFocusScope="True"、コマンド呼び出し元は、ルートからコマンド バインディングのフォーカス要素までのビジュアル ツリー パスも参照します。

于 2012-05-31T13:11:42.987 に答える