2010-05-14 5 views

Répondre

-1

Écoutez l'événement MouseDoubleClick dans le code-behind de la vue et appeler la méthode appropriée sur le ViewModel:

public class MyView : UserControl 
{ 
    ... 

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

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

Cela ne suit pas le modèle MVVM. –

2

Je préfère ajouter un MouseDoubleClickBehaviour et vous pouvez le joindre à tout contrôle, qui se liera à votre ViewModel. L'appel de commandes à partir du code-behind de View crée des dépendances directes que je n'aime pas.

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

Ensuite, vous pouvez le faire dans votre XAML

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

Pourriez-vous ajouter un gestionnaire à un événement double clic de souris sur un objet qui n'était pas un sélecteur MouseDoubleClick sur un bloc de texte par exemple? –