.net - WPF 路由命令是解决问题还是使问题变得更糟?

标签 .net wpf routed-commands

据我了解,命令模式的目标是帮助将 UI 交互与应用程序逻辑分开。使用正确实现的命令,单击“打印”菜单项可能会导致如下交互链:

(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);
        }
    }
} 

我从命令中得到了什么?在我看来,我可以轻松地将命令绑定(bind)事件处理程序中的代码放入按钮的 Click 中。事件。当然,现在我可以将多个 UI 元素与粘贴命令相关联,并且只需要使用一个事件处理程序,但是如果我想粘贴到多个不同的文本框怎么办?我必须使事件处理程序逻辑更复杂或编写更多事件处理程序。所以现在,我觉得我有这个:
(button) ---executes Routed Command---> (Window) ---executes command binding----(command binding)
(logic) <---calls application logic--- (event handler) <-----raises event --------------|

我在这里想念什么?对我来说,它看起来像是额外的间接层。

最佳答案

你可能会混淆概念。
ICommand接口(interface)支持命令模式。这允许您将用户操作抽象为可重用的类。

路由命令是 ICommand 的特殊实现。通过可视化树搜索处理程序。它们对于可以由许多不同控件实现的命令特别有用,并且您希望当前控件处理它。想想复制/粘贴。可能有一大堆控件可以处理它,但是通过使用路由命令,路由命令系统将根据焦点自动找到正确的控件来处理命令。

关于.net - WPF 路由命令是解决问题还是使问题变得更糟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/466699/

相关文章:

c# - 为什么 IDictionary<TKey, TValue> 扩展 ICollection<KeyValuePair<TKey, TValue>>?

.net - 如何确定 DLL 是 COM 还是 .NET?

.net - asp.net应用程序的多用户XML文档 “database”

c# - 列字符串格式

c# - 如何使用 RoutedCommand.Name 属性?

c# - 如何在 C# Windows 窗体中设置 ComboBox 的选定项?

WPF 和 MVVM 问题

c# - WPF 多重绑定(bind)

c# - 无法将路由命令添加到 WPF 中的复选框

wpf - 如何以多窗口模式在应用程序级别启动 RoutedCommand?