gpt4 book ai didi

WPF - 在 ViewModel 中处理 ApplicationCommand

转载 作者:行者123 更新时间:2023-12-04 15:27:59 28 4
gpt4 key购买 nike

我敢打赌这已经被多次回答了,但是......

对于 UserControl 上的按钮将其命令属性设置为 Find (ApplicationCommands.Find) 之类的简单情况,ViewModel 将如何处理该命令?我通常会看到命令处理程序与一个 CommandBinding 连接起来,它被添加到 UIElement 上的 CommandBindings 集合中,但我的 ViewModel 不是从 UIElement 派生的(应该吗?)。命令本身不会公开事件以在它们执行时进行通知,那么我应该在哪里连接以获取该信息?

编辑:如果可能,我想使用库存 WPF 来解决问题。我知道有很多可用的框架可以用于此类事情,但希望保持代码简单。

EDIT2:包括一些示例代码。

<UserControl>
<UserControl.DataContext>
<local:MyViewModel/>
</UserControl.DataContext>

<Button Command="Find"/>
</UserControl>

在哪里:
class MyViewModel
{
// Handle commands from the view here.
}

我可以向 UserControl 添加一个 CommandBinding 来处理 Executed,然后在 MyViewModel 中调用一个假设的 Find 方法来完成实际工作,但这是额外的和不必要的代码。我更喜欢 ViewModel 本身是否处理 Find 命令。一种可能的解决方案是让 MyViewModel 从 UIElement 派生,但这似乎违反直觉。

最佳答案

命令的目的是将生成订单的代码与执行订单的代码分离。因此:如果你想要紧耦合,你最好通过事件来做:

<UserControl ... x:Class="myclass">
...
<Button Click="myclass_find" .../>
...
</UserControl>

对于松散耦合,您需要添加 CommandBinding给您的 UserControl :
<UserControl ... >
<UserControl.DataContext>
<local:MyViewModel/>
</UserControl.DataContext>

<UserControl.CommandBindings>
<Binding Path="myFindCommandBindingInMyViewModel"/>
</UserControl.CommandBindings>
...
<Button Command="ApplicationComamnd.Find" .../>
...
</UserControl>

(不确定语法)

或者您可以添加 CommandBinding给您的 UserControlCommandBindings在构造函数中,从 ViewNodel 中获取值:
partial class MyUserControl : UserControl
{
public MyUSerControl()
{
InitializeComponent();
CommandBinding findCommandBinding =
((MyViewModel)this.DataContext).myFindCommandBindingInMyViewModel;
this.CommandBindings.Add(findCommandBinding);
}
}

关于WPF - 在 ViewModel 中处理 ApplicationCommand,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2328434/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com