WPF中为button添加快捷键(ShortCut)的方法

引言

如果你想为WPF中的button添加某些快捷键,就像CTRL + F,那么你直接在Google中搜索Assign shortcut on button with wpf类似的信息的话,那么搜索出来的一般解决方法就如下所示-->

<Button Name="btnHelp" Content="_Help"></Button> 

这样的效果就是按ALT + H的时候会类似于点击这个button,但是这样实现会有局限性。

为此自己参考了许多资料后,给出了使用InputBindingsKeyBinding实现button的快捷键设置的方案。

在示例程序中,定义了两个button,分别是AddSub,两个button的快捷键分别是CTRL + ACTRL + S,作用分别将右边的数字加1或者减1。

实现

xaml 实现

<Window x:Class="ShortCutButton.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ShortCutButton"
        mc:Ignorable="d"
        Title="ShortCutDemo" Height="100" Width="207" SizeToContent="WidthAndHeight" ResizeMode="NoResize">
    
    <!-- define command -->
    <Window.Resources>
        <ResourceDictionary x:Uid="CommandDict">
            <RoutedCommand x:Uid="AddCommand" x:Key="AddCommand" />
            <RoutedCommand x:Uid="SubCommand" x:Key="SubCommand" />
        </ResourceDictionary>
    </Window.Resources>

    <Window.CommandBindings>
        <CommandBinding x:Uid="AddCommandParameter" Command="{StaticResource AddCommand}" CanExecute="Add_CanExecute" Executed="Add_Executed" />
        <CommandBinding x:Uid="SubCommandParameter" Command="{StaticResource SubCommand}" CanExecute="Sub_CanExecute" Executed="Sub_Executed" />
    </Window.CommandBindings>

    <!-- assign shortcut with command -->
    <Window.InputBindings>
        <KeyBinding x:Uid="AddKeyBinding" Key="A" Modifiers="Ctrl" Command="{StaticResource AddCommand}" />
        <KeyBinding x:Uid="SubkeyBinding" Key="S" Modifiers="Ctrl" Command="{StaticResource SubCommand}"/>
    </Window.InputBindings>
    
    <Grid ShowGridLines="True">
        <Grid.RowDefinitions>
            <RowDefinition Height="auto" />
            <RowDefinition Height="1*" />
        </Grid.RowDefinitions>
        
        <StackPanel Grid.Row="0" HorizontalAlignment="Left" VerticalAlignment="Top">
            <Grid ShowGridLines="True">
                
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="auto" />
                    <ColumnDefinition Width="1*" />
                </Grid.ColumnDefinitions>
                
                <WrapPanel Grid.Column="0" Orientation="Vertical">
                    <!-- margin left top right bottom -->
                    <Button Width="60" Content="Add" FontSize="12" FontStyle="Normal" Margin="5, 5" Background="Azure" Command="{StaticResource AddCommand}">
                    </Button>

                    <Button Width="60" Content="Sub" FontSize="12" FontStyle="Normal" Margin="0,0,0,5" Background="Azure" Command="{StaticResource SubCommand}">
                        
                    </Button>
                </WrapPanel>

                <StackPanel Grid.Column="1">
                    <Label Grid.Column="1" Background="Bisque" FontWeight="Bold" Margin="5,5,5,0">Show Result</Label>
                    <TextBlock Grid.Column="1" Name="showRes" FontSize="12" Text="0" Margin="5, 5" />
                </StackPanel>
                
            </Grid>
        </StackPanel>
    </Grid>
</Window>

代码逻辑实现

private void Add_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
	e.CanExecute = true;
}

private void Add_Executed(object sender, ExecutedRoutedEventArgs e)
{
	var res = Convert.ToInt32(showRes.Text);
	res++;
	showRes.Text = Convert.ToString(res);
}

private void Sub_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
	if (showRes != null && !string.IsNullOrEmpty(showRes.Text))
	{
		e.CanExecute = true;
	}
}

private void Sub_Executed(object sender, ExecutedRoutedEventArgs e)
{
	var res = Convert.ToInt32(showRes.Text);
	res--;
	showRes.Text = Convert.ToString(res);
}

最终效果

67c704dcf9ab19ada2c2db62fe4ca113.png
当你按下CTRL+A的时候,右边数字会自动加1;
当你按下CTRL+S的时候,右边数字会自动减1;

参考资料

Microsoft Q&A

posted @ 2020-09-13 22:24  醉曦  阅读(2784)  评论(0编辑  收藏  举报