mvvm - View 中的 MouseDoubleClick 事件

标签 mvvm binding wpfdatagrid prism-2

当我使用 mvvm 和 Prism 2 时,如何在 View 中绑定(bind) wpfdatagrid 的 MouseDoubleClick 事件。

最佳答案

我更喜欢添加 MouseDoubleClickBehaviour,然后您可以将其附加到任何控件,该控件将绑定(bind)到您的 ViewModel。从 View 的代码隐藏调用命令会创建我不喜欢的直接依赖项。

public static class MouseDoubleClickBehaviour
{
    public static readonly DependencyProperty CommandProperty =
        DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(MouseDoubleClickBehaviour), new UIPropertyMetadata(null, OnCommandChanged));

    public static readonly DependencyProperty CommandParameterProperty =
        DependencyProperty.RegisterAttached("CommandParameter", typeof(object), typeof(MouseDoubleClickBehaviour), new UIPropertyMetadata(null));

    public static ICommand GetCommand(DependencyObject obj)
    {
        return (ICommand)obj.GetValue(CommandProperty);
    }

    public static void SetCommand(DependencyObject obj, ICommand value)
    {
        obj.SetValue(CommandProperty, value);
    }

    public static object GetCommandParameter(DependencyObject obj)
    {
        return obj.GetValue(CommandParameterProperty);
    }

    public static void SetCommandParameter(DependencyObject obj, object value)
    {
        obj.SetValue(CommandParameterProperty, value);
    }

    private static void OnCommandChanged(DependencyObject target, DependencyPropertyChangedEventArgs args)
    {
        var grid = target as Selector;

        ////Selector selector = target as Selector;
        if (grid == null)
        {
            return;
        }

        grid.MouseDoubleClick += (a, b) => GetCommand(grid).Execute(grid.SelectedItem);
    }
}

然后您可以在您的 XAML 中执行此操作
<ListView ...
     behaviours:MouseDoubleClickBehaviour.Command="{Binding Path=ItemSelectedCommand}"
     behaviours:MouseDoubleClickBehaviour.CommandParameter="{Binding ElementName=txtValue, Path=Text}"
 .../>

关于mvvm - View 中的 MouseDoubleClick 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2831911/

相关文章:

c# - 在 WPF MVVM Observable 集合中实现 IsDirty

binding - 协议(protocol)的 Monotouch 绑定(bind)语法

c# - WPF Datagrid "Select All"按钮 - "Unselect All"也是?

WPF ComboBox 在是 DependencyObject 时不显示当前项目

wpf - 获取数据网格中的所有单元格

wpf - 排序不适用于 WPF DataGrid 模板化列?

c# - WPF 反向绑定(bind) OneWayToSource

android - 需要调用API以使用Retrofit更新android mvvm中的 token ,在哪里编写逻辑?

WPF。使用 MVVM 了解 UserControl 中的错误验证

ios - ObjectBinding 和 EnvironmentObject 有什么区别?