WPF 및 C#에서 키보드를 사용하여 파일 메뉴 항목을 선택하는 방법?

StackOverflow https://stackoverflow.com/questions/1405537

  •  05-07-2019
  •  | 
  •  

문제

WPF UI 응용 프로그램을 개발 중입니다.

화면 상단에 메뉴가 있는데 파일이있는 메뉴가 있습니다.

파일 -> 백엔드 기능 (바로 가기 키는 ctrl + b), 종료 (ctrl + x) 하위 메뉴 항목.

하위 메뉴 항목을 클릭하면 해당 창이 열립니다.

따라서 마우스를 사용하여 Ctrl + B 또는 Ctrl + X를 눌러 창을 어떻게 열 수 있습니까?

또한 사용자가 Alt + F를 누르면 파일 메뉴를 볼 수 있도록 파일의 "F"아래에 작은 줄을 표시하는 방법은 어떻게해야합니까?

C#을 사용하여 WPF에서 작업하고 있습니다.

도움이 되었습니까?

해결책

Icommand, Routeduicommand, Inputgesturecollection 및 CommandManager를 조사하고 싶을 것입니다. 조금 더 선행 인프라가 작동하지만 WPF 명령 패턴을 사용하면 기본 메뉴, 컨텍스트 메뉴, 버튼 클릭 등의 명령을 공유 할 수 있습니다. 작업을 사용하는 작업을 사용하여 응용 프로그램의 모든 위치는 활성화됩니다. /일관되게 비활성화하고 코드 반복을 줄이기 위해 하나 더 간접 계층을 추가합니다.

다음 예는 vb.net에 있습니다 (죄송하지만 번역하기가 쉽습니다).

필요한 조치 각각을 ICOMMAND를 구현하는 클래스로 구현하십시오.

Public Class OpenWindowCommand
  Implements ICommand

  Public Function CanExecute(parameter as Object) As Boolean Implements System.Windows.Input.ICommand.CanExecute
    'enter code that determines whether this command should be enabled or not
    'if you are listening to some backend logic that changes this state, you can
    'raise a CanExecuteChanged event
  End Function

  Public Sub Execute(parameter as Object) Implements System.Windows.Input.ICommand.Execute
     'code that you want to run for the action
  End Sub
 End Class

각 명령의 공유 인스턴스를 저장하는 클래스를 만듭니다.

Public Class MyCommands
  Private Shared ReadyOnly openWindowCmd As ICommand = New OpenWindowCommand()
  Private Shared _openWindow as RoutedUICommand

  Shared Sub New()
    'static constructor
    Dim shortcut = New KeyGesture(Key.W, ModifierKeys.Control)
    RegisterCommand(_openWindow, "OpenWindow", "Open...", shortcut, AddressOf ExecuteOpenWindow, AddressOf CanExecuteOpenWindow)
    'add more commands as needed
  End Sub

  Private Shared Sub RegisterCommand(ByRef command as RoutedUICommand, ByVal name as String, ByVal text as String, ByVal gesture as KeyGesture, ByVal executeHandler as ExecutedRoutedEventHandler, ByVal canExecuteHandler as CanExecuteRoutedEventHandler)
    Dim inputs = New InputGestureCollection()
    If gesture IsNot Nothing Then inputs.Add(gesture)
    command = New RoutedUICommand(text, name, GetType(MyCommands), inputs)
    Dim binding = New CommandBinding(command, executeHandler, canExecuteHandler)
    Application.Current.MainWindow.CommandBindings.Add(binding)
    CommandManager.RegisterClassCommandBinding(GetType(Window),binding)
  End Sub

  Public Shared ReadOnly Property OpenWindow() as RoutedUICommand
    Get
      Return _openWindow
    End Get
  End Property
  Public Shared Sub ExecuteOpenWindow(sender as Object, e as ExecutedRoutedEventArgs)
    openCmd.Execute(e.Parameter)
  End Sub
  Public Shared Sub CanExecuteSave(sender as Object, e as CanExecuteRoutedEventArgs)
    e.CanExecute = openCmd.CanExecute(e.Parameter)
    e.Handled = True
  End Sub

End Class

이제 메뉴의 XAML 에서이 명령에 바인딩 할 수 있습니다.

<Window.Resources>
  <local:MyCommands x:Key="commands"/>
</Window.Resources>
...
<MenuItem Name="mnuOpenWindow" Command="{Binding Path=OpenWindow}"/>

이것은 명령을 사용하는 최소 요구 사항보다 조금 더 많지만 합리적으로 큰 응용 프로그램 에서이 추가 인프라가 매우 유용하다는 것을 알았습니다. 명령이 작성되고 등록되면 모든 XAML 문서에서 구속력이있는 것은 사소하며 MyCommands 클래스를 통해 각 조치에 대한 공유 속성을 노출시켜 필요한 경우 코드의 명령에 액세스 할 수 있습니다.

다른 팁

메뉴 항목의 가속기를 나타내는 작은 줄을 추가하려면 XAML에서 밑줄을 사용하십시오.

<MenuItem Header="_File">
    <MenuItem Header="_Backend Features" />
    <MenuItem Header="E_xit" />
</MenuItem>

바로 가기 키는 먼저 사용하지 않는 것이 좋습니다. Ctrl 키 + 엑스 출구의 경우 일반적으로 컷에 사용되기 때문입니다. 일반적으로 종료는 바로 가기 키가 없지만 누릅니다. 대체 + F4 기본 창을 닫으려면 동일한 영향을 미칩니다.

실제 질문과 관련하여 몇 가지 옵션이 있지만 둘 다 Click 이벤트.

첫 번째 옵션은 An을 설정하는 것입니다 InputBinding 각 바로 가기 키에 대해. 메인 창에서 이와 같은 일이 될 것입니다.

Command 속성, 해당 바로 가기의 명령을 나타내는 표현식을 지정해야합니다 (동일하게 사용합니다. Command 정의 할 때 MenuItem, 도). 당신이있는 경우 Commands 수업, 당신은 다음과 같은 것을 할 수 있습니다.

static class Commands
{
    public static ICommand BackendFeaturesCommand = ...;
}

그리고 XAML에서 :

<KeyBinding Key="B" Modifiers="Control"
    Command="{x:Static Commands.BackendFeaturesCommand}" />

다른 옵션은 명령을 RoutedUICommand, 그리고 an을 지정합니다 InputGesture 그것을 위해. 이것은 당신을 위해 바로 가기 키 배선을 처리합니다.

당신은 WPF 응용 프로그램 프레임 워크 (WAF). 이해하기가 아주 간단합니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top