From what I understand, the goal of the Command pattern is to help separate UI interaction from application logic. With properly implemented commands, a click on a "Print" menu item might result in a chain of interaction like this:
(button) ---click executes command----> (command) ---calls Print() in app logic ---> (logic)
This encourages you to separate the UI from the application logic.
I've been looking at WPF commands, and for the most part I see how they've implemented this pattern. However, I feel like to a certain extent they've complicated the Command pattern and managed to implement it in such a way that you are discouraged from separating the UI from application logic.
For example, consider this simple WPF window that has a button to paste text into the text box:
<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>
Here's the code-behind:
namespace WpfApplication1
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
ApplicationCommands.Paste.Execute(null, txtData);
}
}
}
What did I gain from the command? It seems to me that I could have just as easily put the code from the command binding event handler into the button's Click
event. Sure, now I can associate multiple UI elements with the Paste command and I only have to use the one event handler, but what if I want to paste to several different text boxes? I'd have to make the event handler logic more complicated or write more event handlers. So now, I feel like I have this:
(button) ---executes Routed Command---> (Window) ---executes command binding----(command binding)
(logic) <---calls application logic--- (event handler) <-----raises event --------------|
What am I missing here? It looks like an extra layer of indirection to me.