开发者

wpf -shorcut key for image button

开发者 https://www.devze.com 2023-01-10 19:13 出处:网络
On my wpf window, I have got an image button. Does anyone have any idea how to assign a short cut for this button 开发者_StackOverflow社区like \"Cntrl + O\".

On my wpf window, I have got an image button. Does anyone have any idea how to assign a short cut for this button 开发者_StackOverflow社区like "Cntrl + O".

I can put "_" to trigger click on normal button.

<Button Margin="89,73,114,106" Name="button1" Click="button1_Click">
        <StackPanel Name="_StackPanel">
            <Image Source="image.png" ></Image>
        </StackPanel>            
    </Button>


In WPF general keyboard shortcuts (unlike the special case of Alt access keys) aren't assigned to buttons, they are assigned to actions. When you want both a Button (or menu item, multiple buttons, etc.) and a key command for the same action you can use a single Command for both. For a custom RoutedCommand you can assign KeyGestures to fire the command:

    public static RoutedCommand MyCommand { get; private set; }

    static Window1()
    {
        MyCommand = new RoutedCommand("MyCommand", typeof(Window1), new InputGestureCollection { new KeyGesture(Key.O, ModifierKeys.Control) });
    }

    public Window1()
    {
        InitializeComponent();
        CommandBindings.Add(new CommandBinding(MyCommand, (_, e) => MessageBox.Show("Command fired")));
    }

And then also assign it as the Button's Command:

<Button Content="Click Me" Command="{x:Static local:Window1.MyCommand}"/>
0

精彩评论

暂无评论...
验证码 换一张
取 消