1. 程式人生 > 實用技巧 >WPF中為button新增快捷鍵(ShortCut)的方法

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);
}

最終效果


當你按下CTRL+A的時候,右邊數字會自動加1;
當你按下CTRL+S的時候,右邊數字會自動減1;

參考資料

Microsoft Q&A