Welcome

首页 / 软件开发 / .NET编程技术 / 超级简单:如何使用WPF Commands提升你的代码质量

超级简单:如何使用WPF Commands提升你的代码质量2010-11-22 博客园 朱祁林介绍:

WPF Commands是一种非常好的的方式去复用应用程序中功能。在本文提供的 示例中,创建了一个使用WPF的Command模式来对Customer进行排序的示例。 WPFCommand模式非常适合用于在应用程序中的用不同控件调用相同的功能。WPF commands 也能适用于一些其他的情况,例如,如果输入有误,禁用控件。在文 章的CanExecute部分中,我们能进一步了解。

创建一个Command:

为了使用WPF commands,你必须声明静态的command。当你声明这个command ,你也能确定"Input Gestures"也能调用这个命令。你能把 "input gestures" 想象成快捷方式。一些基本的键或者甚至组合键。例如,在示例项目中,我使用 F3这个键作为"input gesture"。

/// <summary>
/// Command to sort the Customers
/// As ou can see the command also hooks to the F3 key of the keyboard
/// </summary>
public static RoutedUICommand SortCustomers = new RoutedUICommand("SortCustomers",
"SortCustomers", typeof(CommandsDemo), new InputGestureCollection (
new InputGesture[] { new KeyGesture(Key.F3, ModifierKeys.None, "Sort Customer") }
));

在这个示例项目中,和用户界面窗体在同一个类(CommandDemo.cs)中创建 command。在实际生活中中的项目,我建议将command声明在更重要的地方,好让 Windows/Components能使用相同的command声明。例如,如果在项目中的另外一 个窗体也能使用customers的排序功能,我会创建一个里面有command的类。这样 ,这个command能被其他窗体轻易地访问。你能把commands 想象成类似于事件的 东西。有人执行该命令,就有人处理命令。在我的脑海中想象这样一幅画 面...

有三个家伙Jon, Mark和在商店工作Patrick 。商店的经理决定让Patrick去 洗地板。Jon说“洗地板”,Patrick 就去执行。Mark说“洗地板”,Patrick就 去执行。所以,基本上Patrick 是Command的处理者,Jon, Mark执行命令致使 Patrick(命令处理者)去做这个操作的。经理说Patrick去洗地板是命令的绑定 。

上面是关于这个模式如何工作的基本解释。也许这个会更令人困惑。按照这 样的方式,我们快忘记了...在WPF类中RoutedCommand类似于RoutedEvents。调 用者执行这个命令,由WPF Visual Tree指挥路线直到CommandBinding来处理这 个命令。在命令处理的时候,通过设置e.Handled = true,将它停止。

现在让我们继续,在定义这个command之后,你必须去做的是如何绑定这个命 令。基本上,这意味着你需要指定谁去执行操作。如下:

//Here we create handle the command binding for the whole window
//so which ever control invokes this command the same handler will handle the command
CommandBindings.Add(new CommandBinding (SortCustomers, SortCustomersHandler));
//command binding for the delet customer
CommandBindings.Add(new CommandBinding (DeleteCustomer, DeleteCustomerHandler, CanExecuteDeleteCustomer));
//handle the CanExecuteChange to set the text of the delete text block
DeleteCustomer.CanExecuteChanged += delegate
{
bool canExecute = AvalonCommandsHelper.CanExecuteCommandSource(deleteButton);
deleteText.Text = canExecute ?
"Delete selected customer" :
"Select customer to delete";
};

}

//handler for the Sort Customers command.
//this event handler will be invoked when some element will execute the SortCustomers Command
private void SortCustomersHandler(object sender, ExecutedRoutedEventArgs e)
{
//default the sort if no parameter is passed
string sortBy = e.Parameter == null ?
"Name" :
e.Parameter.ToString();
//get the view for the list
ICollectionView view = CollectionViewSource.GetDefaultView(customerList.ItemsSource);
view.SortDescriptions.Clear();
//add the new sort description
view.SortDescriptions.Add(
new SortDescription(sortBy, ListSortDirection.Ascending));
view.Refresh();
}