Bri*_*ahy 36 wpf command design-patterns
我做了一些WPF编程,我从未得到过的一件事就是命令模式.每个例子似乎都是内置的,编辑,剪切,粘贴.任何人都有自定义命令的最佳实践示例或建议?
Nid*_*ocu 38
啊哈!我可以回答一个问题!首先,我要提一下,我个人发现在代码中而不是在XAML中更容易定义和连接命令.它允许我比所有XAML方法更灵活地连接命令的处理程序.
您应该弄清楚您想要的命令以及它们的相关内容.在我的应用程序中,我目前有一个类来定义重要的应用程序命令,如下所示:
public static class CommandBank
{
/// Command definition for Closing a window
public static RoutedUICommand CloseWindow { get; private set; }
/// Static private constructor, sets up all application wide commands.
static CommandBank()
{
CloseWindow = new RoutedUICommand();
CloseWindow.InputGestures.Add(new KeyGesture(Key.F4, ModifierKeys.Alt));
// ...
}
Run Code Online (Sandbox Code Playgroud)
现在,因为我想将代码保持在一起,使用仅代码方法的命令允许我在上面的类中放置以下方法:
/// Closes the window provided as a parameter
public static void CloseWindowExecute(object sender, ExecutedRoutedEventArgs e)
{
((Window)e.Parameter).Close();
}
/// Allows a Command to execute if the CommandParameter is not a null value
public static void CanExecuteIfParameterIsNotNull(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = e.Parameter != null;
e.Handled = true;
}
Run Code Online (Sandbox Code Playgroud)
第二种方法甚至可以与其他命令共享,而不必在整个地方重复它.
一旦定义了这样的命令,就可以将它们添加到任何UI.在下面,一旦Window已加载,我将命令绑定添加到Window和MenuItem,然后使用循环向Window添加输入绑定,以便为所有命令绑定执行此操作.传递的参数是它自己的Window,因此上面的代码知道要尝试和关闭的Window.
public partial class SimpleWindow : Window
{
private void WindowLoaded(object sender, RoutedEventArgs e)
{
// ...
this.CommandBindings.Add(
new CommandBinding(
CommandBank.CloseWindow,
CommandBank.CloseWindowExecute,
CommandBank.CanExecuteIfParameterIsNotNull));
foreach (CommandBinding binding in this.CommandBindings)
{
RoutedCommand command = (RoutedCommand)binding.Command;
if (command.InputGestures.Count > 0)
{
foreach (InputGesture gesture in command.InputGestures)
{
var iBind = new InputBinding(command, gesture);
iBind.CommandParameter = this;
this.InputBindings.Add(iBind);
}
}
}
// menuItemExit is defined in XAML
menuItemExit.Command = CommandBank.CloseWindow;
menuItemExit.CommandParameter = this;
// ...
}
// ....
}
Run Code Online (Sandbox Code Playgroud)
然后我还为WindowClosing和WindowClosed事件提供了事件处理程序,我建议你尽可能地使命令的实际执行尽可能小.就像在这种情况下,如果有未保存的数据,我没有尝试放置试图阻止Window关闭的代码,我将该代码牢牢地保存在WindowClosing事件中.
如果您有任何后续问题,请告诉我.:)
我在去年http://blogs.vertigo.com/personal/alanl/Blog/archive/2007/05/31/commands-in-wpf.aspx上写了一篇关于WPF命令的大量资源以及一个例子.
粘贴在这里:
Adam Nathan关于WPF中重要新概念的示例章节:命令
Keyvan Nayyeri:如何向自定义WPF控件添加命令
Ian Griffiths:Avalon输入,命令和处理程序
MSDN Library:ApplicationCommands类
MSDN Library:NavigationCommands类
MSDN Library:ComponentCommands类
同样埋藏在WPF SDK示例中,我已经扩展了RichTextBox编辑的一个很好的示例.你可以在这里找到它:RichTextEditor.zip