WPF의 InputBinding 이해하기: MouseBinding과 KeyBinding 활용

이전 문서에서는 WPF 명령 시스템의 일부를 살펴보았습니다. 여기서는 CommandBinding과 데이터 바인딩 두 가지 방법으로 Button 컨트롤에 명령(ICommand)을 연결하는 방법을 소개했습니다.

예제 1. CommandBinding 사용

<Window.Resources>
    <RoutedCommand x:Key="CustomCommand"/>
</Window.Resources>
<Window.CommandBindings>
    <CommandBinding Command="{StaticResource CustomCommand}" Executed="ExecuteCommand" CanExecute="CanExecuteCommand"/>
</Window.CommandBindings>
<Grid>
    <Button Width="200" Height="100" Content="클릭하세요" Command="{StaticResource CustomCommand}"/>
</Grid>

예제 2. 데이터 바인딩 사용 (데이터 소스 내에서 ICommand 인터페이스를 구현한 객체와 바인딩)

<Grid>
    <Button Width="200" Height="100" Content="클릭하세요" Command="{Binding Cmd}"/>
</Grid>

여기서 Cmd는 DataContext 내에 있는 ICommand 인터페이스를 구현한 객체입니다.

위의 두 예제에서는 Button 클릭을 통해 명령이 실행됩니다. 그러나 실제 개발 환경에서는 버튼 외에도 키보드나 마우스 이벤트로 명령을 실행해야 할 경우가 있습니다. 이런 경우, UIElement의 InputBindings 속성을 이용할 수 있습니다.

요구 사항 1. 특정 키 조합(Ctrl + N)을 눌렀을 때 "Hello world" 메시지 박스 표시

<Window.InputBindings>
    <KeyBinding Command="{Binding KeyboardCmd}" Gesture="Ctrl+N"/>
</Window.InputBindings>
public partial class MainView : Window
{
    public MyCommand KeyboardCmd { get; }

    public MainView()
    {
        InitializeComponent();
        DataContext = this;
        KeyboardCmd = new MyCommand(ExecuteKeyboardCommand);
    }

    private void ExecuteKeyboardCommand(object param)
    {
        MessageBox.Show("Hello world");
    }
}

요구 사항 2. 마우스 오른쪽 버튼 더블 클릭 시 "你好,世界" 메시지 박스 표시

<Window.InputBindings>
    <MouseBinding Command="{Binding MouseCmd}" MouseAction="RightDoubleClick"/>
</Window.InputBindings>
public partial class MainView : Window
{
    public MyCommand MouseCmd { get; }

    public MainView()
    {
        InitializeComponent();
        DataContext = this;
        MouseCmd = new MyCommand(ExecuteMouseCommand);
    }

    private void ExecuteMouseCommand(object param)
    {
        MessageBox.Show("你好,世界");
    }
}

두 예제 모두 InputBinding의 파생 클래스인 KeyBinding과 MouseBinding을 사용하였습니다.

KeyBinding은 키보드 입력을 명령에 연결하며, 주요 속성은 Command, Gesture, ModifierKeys 및 Key입니다. .NET에서는 Gesture(KeyGesture) 또는 ModifierKeys + Key 방식을 지원합니다. 그러나 잘못된 사용법도 존재합니다:

  • Gesture와 ModifierKeys+Key 동시 사용
  • Gesture에 Key만 지정하고 ModifierKeys 미지정
  • ModifierKeys만 지정하고 Key 미지정

.NET에서는 XAML에서 Gesture 사용을 권장하지만, None + Key 형태는 지원되지 않습니다.

MouseBinding은 마우스 동작을 명령에 연결하며, Gesture(MouseGesture)와 MouseAction 두 가지 방법으로 명령을 연결할 수 있습니다. 이 두 방식은 동시에 사용될 경우 마지막 선언된 방식만 유효합니다.

UIElement의 InputBindings는 어떻게 동작할까요?

반해 컴파일 도구를 통해 확인해보면, 마우스나 키보드 동작 시 InputBindings 관련 코드는 직접적으로 호출되지 않습니다. 하지만 UIElement 클래스 내부에서 InputBindingsCollection 필드를 통해 관리되는 것을 볼 수 있습니다.

태그: WPF InputBinding KeyBinding MouseBinding ICommand

7월 3일 18:59에 게시됨