Owe*_*enP 5 .net wpf routed-commands
据我所知,Command模式的目标是帮助将UI交互与应用程序逻辑分开.使用正确实现的命令,单击"打印"菜单项可能会产生一系列交互,如下所示:
(button) ---click executes command----> (command) ---calls Print() in app logic ---> (logic)
Run Code Online (Sandbox Code Playgroud)
这鼓励您将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>
Run Code Online (Sandbox Code Playgroud)
这是代码隐藏:
namespace WpfApplication1
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
ApplicationCommands.Paste.Execute(null, txtData);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我从命令中获得了什么?在我看来,我可以轻松地将命令绑定事件处理程序中的代码放入按钮的Click
事件中.当然,现在我可以将多个UI元素与粘贴命令相关联,我只需要使用一个事件处理程序,但是如果我想粘贴到几个不同的文本框呢?我必须使事件处理程序逻辑更复杂或编写更多的事件处理程序.所以现在,我觉得我有这个:
(button) ---executes Routed Command---> (Window) ---executes command binding----(command binding)
(logic) <---calls application logic--- (event handler) <-----raises event --------------|
Run Code Online (Sandbox Code Playgroud)
我在这里错过了什么?它看起来像是一个额外的间接层.
除了已经提到的内容之外,您在特定的粘贴示例中忘记的是 CommandTarget 和 CommandParameter 属性。对于粘贴,您可以通过设置为 CommandTarget 来指定文本框。
当想要从不同的控件使用相同的 RoutedCommand 时,这些属性是绝对必要的。它们允许您向执行处理程序提供有关调用命令的上下文的一些信息。
归档时间: |
|
查看次数: |
2861 次 |
最近记录: |