2014-07-16 9 views
2

간단한 예제로 WPF에서 키 바인딩을 배우려고합니다. 여기 xaml을 수정하여 버튼 핫키를 만드는 방법은 무엇입니까?

내 XAML 파일입니다

<Window.Resources> 
    <RoutedUICommand x:Key="myNewCommand"></RoutedUICommand> 
</Window.Resources> 

<Window.CommandBindings> 
    <CommandBinding Command="{StaticResource myNewCommand}" Executed="Button_Click"></CommandBinding> 
</Window.CommandBindings> 

<Window.InputBindings> 
    <KeyBinding Command="{Binding myNewCommand}" Key="B" /> 
</Window.InputBindings> 

<Grid> 
    <Button Command="{Binding myNewCommand}" Click="Button_Click" Content="Click Here"/> 

</Grid> 

그리고이 Button_Click에 대한 뒤에 코드 :

private void Button_Click(object sender, RoutedEventArgs e) 
    { 
     MessageBox.Show("hello"); 
    } 

나는 버튼을 클릭 할 때 "안녕하세요"메시지,하지만 응답 때 키보드의 "B"를 누르십시오. Button_click을 변경하지 않고이 바인딩을 만들고 싶습니다. XAML에서만 할 수 있습니까? 방법?

+0

내가 전에있는 InputBindings을 사용하지 않은,하지만 myNewCommand는'StaticResource'이다. 귀하의'InputBindings' 명령은 아마도'CommandBindings'에서와 같이'{StaticResource myNewCommand}'를 읽어야합니다. – Alex

+0

감사합니다! 그것은 문제를 해결했습니다. –

답변

2

명령 바인딩이 올바르지 않습니다. {Binding myNewCommand}{Binding Source={StaticResource myNewCommand}}으로 대체해야합니다. 이미 명령을 바인딩 한 경우에는 단추에 클릭 처리기가있을 필요가 없습니다.

<Window.Resources> 
    <RoutedUICommand x:Key="myNewCommand"/> 
</Window.Resources> 
<Window.CommandBindings> 
    <CommandBinding Command="{StaticResource myNewCommand}" 
        Executed="MyCommandExecuted"/> 
</Window.CommandBindings> 
<Window.InputBindings> 
    <KeyBinding Command="{Binding Source={StaticResource myNewCommand}}" Key="B" /> 
</Window.InputBindings> 
<Grid> 
    <Button Command="{Binding Source={StaticResource myNewCommand}}" 
      Content="Click Here"/> 
</Grid> 

Executed 핸들러 :

private void MyCommandExecuted(object sender, RoutedEventArgs e) 
{ 
    MessageBox.Show("hello"); 
}