【问题标题】:What is the best way to handel click-events in MVVM?在 MVVM 中处理点击事件的最佳方法是什么?
【发布时间】:2011-04-12 13:33:35
【问题描述】:

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

我找到了两种解决方案:

使用中继命令:

RelayCommand buttonAddCategory_Click;
public ICommand ButtonAddCategory_Click
{
    get
    {
        return buttonAddCategory_Click ?? (buttonAddCategory_Click = new RelayCommand(param => this.AddCategory(),
                                                                                      param => true));
    }
}

专业人士:?;相反:如果我要更改 ui 元素 like focus

,则需要解决事件

附加行为:

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

专业人士:您有 RoutedEventArgs 用于在 ui 上进行更改; contra:访问其他控件?

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

【问题讨论】:

    标签: wpf mvvm relaycommand attachedbehaviors


    【解决方案1】:

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

    • 如果您在 VM 上定义了状态更改,请公开一个 RelayCommand,然后可以将其绑定到触发它的东西。在 99.9% 的情况下,这是一个按钮/菜单项。可以轻松使用的东西。剩下的情况-> 可能需要一些解决方法,例如从视图中调用方法。 因此,如果您真的针对 VM,应该使用 RelayCommand。

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

    hth, 马丁

    【讨论】:

      【解决方案2】:

      我喜欢这个主意:

      UI 逻辑,例如打开新窗口、显示/隐藏元素等。您将其保留在代码隐藏中。

      当这个“点击”应该对模型执行某些操作时,调用该操作。

      因此,关闭窗口并保存内容的按钮将被定义为:

      <Button  Name="SaveBtnr" VerticalAlignment="Bottom" 
              Command="{Binding Save}" Click="OnSaveClick"
              CommandParameter="{Binding}">Save</Button>
      

      处理程序将是:

      private void OnSaveClick(object sender, RoutedEventArgs e)
          {
              //Do UI Stuff
          }
      

      然后你的命令:

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

      【讨论】:

        猜你喜欢
        • 2014-10-20
        • 1970-01-01
        • 2017-03-27
        • 1970-01-01
        • 2010-11-03
        • 2019-09-29
        • 2013-10-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多