Событие MouseDoubleClick в представлении - PullRequest
1 голос
/ 14 мая 2010

Как связать событие MouseDoubleClick wpfdatagrid в представлении, когда я использую mvvm и Prism 2.

Ответы [ 2 ]

2 голосов
/ 07 сентября 2010

Я предпочитаю добавить MouseDoubleClickBehaviour, а затем вы можете прикрепить его к любому элементу управления, который будет привязан к вашей 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}"
 .../>
0 голосов
/ 14 мая 2010

Прослушайте событие MouseDoubleClick в коде позади View и вызовите соответствующий метод в ViewModel:

public class MyView : UserControl 
{
    ...

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

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