【问题标题】:MouseDoubleClick event in View视图中的 MouseDoubleClick 事件
【发布时间】:2011-02-19 09:19:14
【问题描述】:

当我使用 mvvm 和 Prism 2 时,如何在视图中绑定 wpfdatagrid 的 MouseDoubleClick 事件。

【问题讨论】:

    标签: mvvm binding wpfdatagrid prism-2


    【解决方案1】:

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

    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}"
     .../>
    

    【讨论】:

    • 您能否在文本块上的非 Selector MouseDoubleClick 对象上为鼠标双击事件添加处理程序?
    【解决方案2】:

    在 View 的代码隐藏中监听 MouseDoubleClick 事件并在 ViewModel 上调用相应的方法:

    public class MyView : UserControl 
    {
        ...
    
        private MyViewModel ViewModel { get { return DataContext as MyViewModel; } }
    
        private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            ViewModel.OpenSelectedItem();
        }
    

    【讨论】:

    • 这不遵循 MVVM 模式。
    猜你喜欢
    • 2011-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-30
    • 1970-01-01
    相关资源
    最近更新 更多