How do I bind MouseDoubleClick event of wpfdatagrid in the view as I'm using mvvm and Prism 2.
A:
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();
}
jbe
2010-05-14 10:43:13
A:
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}"
.../>
WiT8litZ
2010-09-07 06:15:22