如何在mvvm中绑定moused双击命令
我有listview,当有人双击任何位置时,我希望显示新窗口。 但我有mvvm应用程序,我不希望在xaml文件的代码后面有任何函数,如下所示: 如何绑定一个Command来双击DataGrid中的一行以及许多其他样本。 我想在viewmodel文件中有方法并将其绑定如下:
谢谢
这是根据列表中单击的项触发命令(在ViewModel中)的方法的工作示例。 ViewModel中的命令将获取“clicked”项作为其参数。
我正在使用Textblock.InputBindings,它可能是Blachshma链接的Blend SDK的一部分,但您不需要任何其他DLL来实现此function。
在我的示例中,ViewModel绑定到UserControl的DataContext,这就是我需要使用RelativeSource FindAncestor从我的TextBlock中查找ViewModel的原因。
编辑 :通过将TextBlock的宽度绑定到ListBox的ActualWidth来修复宽度问题。
只有一个问题,双击只有在文本块中的文本内部单击时才会起作用,即使列表本身更宽。
您可以使用附加属性绑定所需的任何事件。
对于MouseDoubleClick
:
namespace Behavior { public class MouseDoubleClick { public static DependencyProperty CommandProperty = DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(MouseDoubleClick), new UIPropertyMetadata(CommandChanged)); public static DependencyProperty CommandParameterProperty = DependencyProperty.RegisterAttached("CommandParameter", typeof(object), typeof(MouseDoubleClick), new UIPropertyMetadata(null)); public static void SetCommand(DependencyObject target, ICommand value) { target.SetValue(CommandProperty, value); } public static void SetCommandParameter(DependencyObject target, object value) { target.SetValue(CommandParameterProperty, value); } public static object GetCommandParameter(DependencyObject target) { return target.GetValue(CommandParameterProperty); } private static void CommandChanged(DependencyObject target, DependencyPropertyChangedEventArgs e) { Control control = target as Control; if (control != null) { if ((e.NewValue != null) && (e.OldValue == null)) { control.MouseDoubleClick += OnMouseDoubleClick; } else if ((e.NewValue == null) && (e.OldValue != null)) { control.MouseDoubleClick -= OnMouseDoubleClick; } } } private static void OnMouseDoubleClick(object sender, RoutedEventArgs e) { Control control = sender as Control; ICommand command = (ICommand)control.GetValue(CommandProperty); object commandParameter = control.GetValue(CommandParameterProperty); command.Execute(commandParameter); } } }
在Xaml:
最简单的方法是使用System.Windows.Interactivity
和Microsoft.Expression.Interactions
(通过Blend SDK免费提供)
首先,在视图中添加以下命名空间
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
接下来,捕获DoubleClick事件并将其传递给命令:
注意:使用的EventToCommand
是MVVM Light Toolkit中的一个 ,可以在这里下载。 它的作用是在触发事件后立即执行命令( myFunction
)。
这是基于myFunction
命令位于ListView用户的DataContext中的假设。 否则,将EventToCommand的绑定修改为命令所在的位置。