开发者

MouseDoubleClick event in View

How do I bind MouseDoubleClick event of wpfd开发者_开发知识库atagrid in the view as I'm using mvvm and Prism 2.


I prefer adding a MouseDoubleClickBehaviour and then you can attach it to any control, which will bind to your ViewModel. Calling commands from the View's code-behind creates direct dependencies which I don't like.

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

Then you can do this in your XAML

<ListView ...
     behaviours:MouseDoubleClickBehaviour.Command="{Binding Path=ItemSelectedCommand}"
     behaviours:MouseDoubleClickBehaviour.CommandParameter="{Binding ElementName=txtValue, Path=Text}"
 .../>


Listen to the MouseDoubleClick event in the code-behind of the View and call the appropriate method on the ViewModel:

public class MyView : UserControl 
{
    ...

    private MyViewModel ViewModel { get { return DataContext as MyViewModel; } }

    private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        ViewModel.OpenSelectedItem();
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜