据我所知,命令模式的目标是帮助将UI交互与应用程序逻辑分开。有了正确执行命令,在“打印”菜单项,点击可能会导致这样的互动链条:WPF路由命令是解决问题还是让问题变得更糟?
(button) ---click executes command----> (command) ---calls Print() in app logic ---> (logic)
这鼓励你的UI与应用逻辑分离。
我一直在寻找WPF命令,并在大多数情况下,我看他们是如何实现这种模式。不过,我觉得在某种程度上他们已经将命令模式复杂化并且设法实现它,使得你不鼓励将UI与应用程序逻辑分开。
例如,假设有一个按钮将文本粘贴到文本框这个简单的WPF窗口:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Window.CommandBindings>
<CommandBinding Command="ApplicationCommands.Paste"
Executed="CommandBinding_Executed"/>
</Window.CommandBindings>
<StackPanel>
<TextBox x:Name="txtData" />
<Button Command="Paste" Content="Paste" />
</StackPanel>
</Window>
这里的隐藏代码:
namespace WpfApplication1
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
ApplicationCommands.Paste.Execute(null, txtData);
}
}
}
我是怎么从增益命令?在我看来,我可以轻松地将来自命令绑定事件处理程序的代码放入按钮的Click
事件中。当然,现在我可以将多个UI元素与Paste命令关联起来,我只需要使用一个事件处理程序,但是如果我想要粘贴到多个不同的文本框呢?我必须让事件处理程序的逻辑更加复杂或者编写更多的事件处理程序。所以现在,我觉得我有这个:
(button) ---executes Routed Command---> (Window) ---executes command binding----(command binding)
(logic) <---calls application logic--- (event handler) <-----raises event --------------|
我在这里失踪了什么?它看起来像一个额外的间接层我。
我昨天晚上看了一本关于命令的书,发现了这些信息,然后很快感觉就像是一种涂料。 – OwenP 2009-01-22 16:17:01