簡體   English   中英

wpf菜單項的鍵盤快捷鍵

[英]Keyboard shortcut for wpf menu item

我正在嘗試使用我的xaml代碼中的菜單項添加鍵盤快捷鍵

<MenuItem x:Name="Options" Header="_Options" InputGestureText="Ctrl+O" Click="Options_Click"/>

使用Ctrl + O.

但它沒有用 - 它沒有調用Click選項。

這有什么解決方案嗎?

InputGestureText只是一個文本。 它不會將鍵綁定到MenuItem

此屬性不會將輸入手勢與菜單項相關聯; 它只是將文本添加到菜單項。 應用程序必須處理用戶的輸入以執行操作

您可以做的是在窗口中使用指定的輸入手勢創建RoutedUICommand

public partial class MainWindow : Window
{
    public static readonly RoutedCommand OptionsCommand = new RoutedUICommand("Options", "OptionsCommand", typeof(MainWindow), new InputGestureCollection(new InputGesture[]
        {
            new KeyGesture(Key.O, ModifierKeys.Control)
        }));

    //...
}

然后在XAML中將該命令綁定到針對MenuItem某個方法集。 在這種情況下, InputGestureTextHeader都將從RoutedUICommand提取,因此您無需針對MenuItem進行設置

<Window.CommandBindings>
    <CommandBinding Command="{x:Static local:MainWindow.OptionsCommand}" Executed="Options_Click"/>
</Window.CommandBindings>
<Menu>
    <!-- -->
    <MenuItem Command="{x:Static local:MainWindow.OptionsCommand}"/>
</Menu>

你應該以這種方式成功:通過使用KeyBindings 定義MenuItem快捷方式

<Window.CommandBindings> <CommandBinding Command="New" Executed="CommandBinding_Executed" /> </Window.CommandBindings> <Window.InputBindings> <KeyBinding Key="N" Modifiers="Control" Command="New"/> </Window.InputBindings>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM