2012-05-31 2 views
3

RoutedCommands를 사용하는 방법을 이해하려고합니다. Button에 CommandTarget을 지정하지 않으면 모든 포커스 된 요소가 명령을 수신한다는 인상하에있었습니다. 하지만 어떤 이유로 작동하지 않습니다. 내가하지만 물론 지정된 텍스트 상자에, 작동 버튼에 CommandTarget을 추가하는 경우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"/> 
    </Grid> 
</Window> 

: 여기에 작동하지 않습니다 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" 
        CommandTarget="{Binding ElementName=textBox1}"/> 
    </Grid> 
</Window> 

어떻게 어떤 초점을 맞춘 요소가 명령을 수신 할 수 있습니까?

감사합니다.

답변

6

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" 인 경우 명령 호출자는 명령 바인딩의 루트에서 포커스 요소까지의 시각적 트리 경로를 조사합니다.

+0

박스에서 텍스트를 입력하고 선택한 후에도 버튼이 활성화되지 않기 때문에 (적어도이 단계에서는)별로 도움이되지 않습니다. – luddet

+0

@luddet : 답변을 업데이트했습니다. –

+0

원더풀! 그게 잘 작동합니다! 고마워요! – luddet