WPF教程之 实现自定义WPF命令

WPF命令:

实现自定义WPF命令

在上一章中,我们研究了使用WPF中已定义的命令的各种方法,当然您也可以实现自己的命令。它非常简单,一旦你完成它,就可以使用自己的命令,就像在WPF中定义的命令一样。

开始实现自己的命令的最简单方法是使用包含它们的静态类。然后将每个命令作为static字段添加到此类,允许您在应用程序中使用它们。由于WPF由于一些奇怪的原因,没有实现退出/离开命令,我决定为我们的自定义命令示例实现一个。它看起来像这样:

<Window x:Class="WpfTutorialSamples.Commands.CustomCommandSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:self="clr-namespace:WpfTutorialSamples.Commands"
        Title="CustomCommandSample" Height="150" Width="200">
    <Window.CommandBindings>
        <CommandBinding Command="self:CustomCommands.Exit" CanExecute="ExitCommand_CanExecute" Executed="ExitCommand_Executed" />
    </Window.CommandBindings>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Menu>
            <MenuItem Header="File">
                <MenuItem Command="self:CustomCommands.Exit" />
            </MenuItem>
        </Menu>
        <StackPanel Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center">
            <Button Command="self:CustomCommands.Exit">Exit</Button>
        </StackPanel>
    </Grid>
</Window>
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Input;

namespace WpfTutorialSamples.Commands
{
	public partial class CustomCommandSample : Window
	{
		public CustomCommandSample()
		{
			InitializeComponent();
		}

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

		private void ExitCommand_Executed(object sender, ExecutedRoutedEventArgs e)
		{
			Application.Current.Shutdown();
		}
	}

	public static class CustomCommands
	{
		public static readonly RoutedUICommand Exit = new RoutedUICommand
			(
				"Exit",
				"Exit",
				typeof(CustomCommands),
				new InputGestureCollection()
				{
					new KeyGesture(Key.F4, ModifierKeys.Alt)
				}
			);

		//Define more commands here, just like the one above
	}
}

WPF教程之 实现自定义WPF命令

在标记中,我定义了一个带菜单和按钮的非常简单的界面,它们都使用我们新的自定义Exit命令。此命令在我们自己的CustomCommands类中的代码隐藏中定义,然后在窗口的CommandBindings集合中引用,我们在其中分配应该用于执行/检查是否允许执行的事件。

所有这些都与前一章中的示例类似,只是我们从我们自己的代码引用命令(使用顶部定义的“self”命名空间)而不是内置命令。

在Code-behind中,我们响应命令的两个事件:一个事件只允许命令一直执行,因为对于exit / quit命令通常是这样,而另一个事件调用Shutdown方法将终止我们的命令应用。一切都很简单。

如前所述,我们将Exit命令实现为静态CustomCommands类的字段。有几种方法可以在命令上定义和分配属性,但是我选择了更紧凑的方法(如果放在同一条线上会更紧凑,但为了便于阅读,我在这里添加了换行符)所有这一切都通过构造函数。参数是命令的文本/标签,命令的名称,所有者类型,然后是InputGestureCollection,允许我为命令定义默认快捷方式(Alt + F4)。

小结

实现自定义WPF命令几乎与使用内置命令一样简单,它允许您在应用程序中为每个目的使用命令。这使得在多个地方重复使用操作变得非常容易,如本章示例所示。

作者:terry,如若转载,请注明出处:https://www.web176.com/wpf/16002.html

(0)
打赏 支付宝 支付宝 微信 微信
terryterry
上一篇 2023年4月19日
下一篇 2023年4月19日

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注