Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Wpf 在MVVM中处理单击事件的最佳方法是什么?_Wpf_Mvvm_Relaycommand_Attachedbehaviors - Fatal编程技术网

Wpf 在MVVM中处理单击事件的最佳方法是什么?

Wpf 在MVVM中处理单击事件的最佳方法是什么?,wpf,mvvm,relaycommand,attachedbehaviors,Wpf,Mvvm,Relaycommand,Attachedbehaviors,在MVVM中处理单击事件的最佳方法是什么?有没有最好的办法 我找到了两种解决办法: 使用relaycommand: RelayCommand buttonAddCategory_Click; public ICommand ButtonAddCategory_Click { get { return buttonAddCategory_Click ?? (buttonAddCategory_Click = new RelayCommand(param =>

在MVVM中处理单击事件的最佳方法是什么?有没有最好的办法

我找到了两种解决办法:

使用relaycommand:

RelayCommand buttonAddCategory_Click;
public ICommand ButtonAddCategory_Click
{
    get
    {
        return buttonAddCategory_Click ?? (buttonAddCategory_Click = new RelayCommand(param => this.AddCategory(),
                                                                                      param => true));
    }
}
赞成:?;相反:如果我要更改ui元素,需要解决事件问题

随附行为:

public static bool GetIsResetMouseLeftButtonDown(TreeView treeView)
{
    return (bool)treeView.GetValue(IsResetMouseLeftButtonDownProperty);
}
public static void SetIsResetMouseLeftButtonDown(TreeView treeViewItem, bool value)
{
    treeViewItem.SetValue(IsResetMouseLeftButtonDownProperty, value);
}
public static readonly DependencyProperty IsResetMouseLeftButtonDownProperty =
    DependencyProperty.RegisterAttached("PreviewMouseLeftButtonDown", typeof(bool), typeof(TreeViewBehavior),
    new UIPropertyMetadata(false, OnIsMouseLeftButtonDownChanged));
赞成:您已经为ui上的更改发送了ventarg;contra:访问其他控件


现在我使用两种解决方案。按钮中的RellayCommand(带有ui更新事件)和附加的treeview行为,以便在用户单击时取消选择treeview项。

对我来说,这个问题没有简单的答案。 我就是这么看的:

  • 如果您在VM上有一个已定义的状态更改,请公开一个RelayCommand,该命令可以绑定到触发它的某个对象。在99.9%的情况下,这是一个按钮/菜单项。一些容易使用的东西。剩下的案例->可能需要一些变通方法,比如从视图中调用方法。 因此,如果您真的以VM为目标,那么应该使用RelayCommand

  • 另一方面,焦点更改是与视图相关的功能。我觉得这和WM无关。这意味着对我来说,它应该在视图中实现。所以对我来说,我甚至会选择一个直接的事件处理程序来完成这项工作

嗯,, 马丁

我喜欢这个主意:

UI逻辑,如打开新窗口、显示/隐藏元素等。您可以在代码中保留这些逻辑

当此“单击”应该对模型执行某些操作时,调用该操作

因此,关闭窗口并保存内容的按钮定义如下:

<Button  Name="SaveBtnr" VerticalAlignment="Bottom" 
        Command="{Binding Save}" Click="OnSaveClick"
        CommandParameter="{Binding}">Save</Button>
然后你的命令:

  public void SaveCommand(object parameter)
    {
        //SaveStuff            
    }
  public void SaveCommand(object parameter)
    {
        //SaveStuff            
    }