WPF DataGrid: CommandBinding to a double click instead of using Events
Solution 1
No need for attached behaviors or custom DataGrid subclasses here.
In your DataGrid
, bind ItemsSource
to an ICollectionView
. The trick here is to set IsSynchronizedWithCurrentItem="True"
which means the selected row will be the current item.
The second part of the trick is to bind CommandParameter
to the current item with the forward slash syntax.
When a row is double clicked, the command will be executed with the clicked row as argument.
<DataGrid
ItemsSource="{Binding CollectionView}"
IsSynchronizedWithCurrentItem="True">
<DataGrid.InputBindings>
<MouseBinding
MouseAction="LeftDoubleClick"
Command="{Binding DoubleClickCommand}"
CommandParameter="{Binding CollectionView/}"/>
</DataGrid.InputBindings>
</DataGrid>
This is how a (simplified) version of the view model would look:
class MyViewModel
{
public ICollectionView CollectionView { get; set; }
public ICommand DoubleClickCommand { get; set; }
}
Solution 2
Another solution is to add input bindings, and to bind the selectedItem to a property so you'll know which one was selected:
<DataGrid SelectedItem="{Binding SelectedItem}">
<DataGrid.InputBindings>
<MouseBinding Gesture="LeftDoubleClick" Command="{Binding SomeCommand}"/>
</DataGrid.InputBindings>
</DataGrid>
Solution 3
Use this library
Sample binding to datagrid event:
<DataGrid xmlns:command="clr-namespace:AttachedCommandBehavior;assembly=AttachedCommandBehavior"
command:CommandBehavior.Event="MouseDoubleClick"
command:CommandBehavior.Command="{Binding TestCommand}" />
But this code is better, because raises on row clicks only:
<DataGrid>
<DataGrid.Resources>
<Style TargetType="DataGridRow">
<Setter Property="command:CommandBehavior.Event" Value="MouseDoubleClick"/>
<Setter Property="command:CommandBehavior.Command" Value="{Binding DataContext.TestCommand, RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}}"/>
</Style>
</DataGrid.Resources>
</DataGrid>
Solution 4
Or, you could create a derived class
public class CustomDataGrid : DataGrid
{
public ICommand DoubleClickCommand
{
get { return (ICommand)GetValue(DoubleClickCommandProperty); }
set { SetValue(DoubleClickCommandProperty, value); }
}
// Using a DependencyProperty as the backing store for DoubleClickCommand. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DoubleClickCommandProperty =
DependencyProperty.Register("DoubleClickCommand", typeof(ICommand), typeof(CustomDataGrid), new UIPropertyMetadata());
public CustomDataGrid()
: base()
{
this.PreviewMouseDoubleClick += new MouseButtonEventHandler(CustomDataGrid_PreviewMouseDoubleClick);
}
void CustomDataGrid_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (DoubleClickCommand != null)
{
DoubleClickCommand.Execute(null);
}
}
}
and in XAML simply bind to the newly created command
<CustomDataGrid DoubleClickCommand="{Binding DoubleClickCommand}">
myermian
Updated on June 27, 2020Comments
-
myermian almost 4 years
I know how to use the MouseDoubleClick event with my DataGrid to grab the selectedvalue, but how would one go about using command bindings instead? That way my ViewModel can handle the logic.
So far I have the following:
<DataGrid Name="TestGrid" Grid.Row="2" Grid.ColumnSpan="2" AutoGenerateColumns="True" MouseDoubleClick="TestGrid_MouseDoubleClick" ItemsSource="{Binding Registrations}" SelectedValue="{Binding CurrentRegistration}" IsReadOnly="True" AlternationCount="2" GridLinesVisibility="None">
I want to get rid of MouseDoubleClick and replace it appropriately.
-
myermian about 13 yearsI like the library, but it seems to contain more than what I need (for the moment). I'll look at the library and if I need more than the double click command then perhaps this will contain other commands I wouldn't mind having.
-
vortexwolf about 13 years@myermian You can also take a look at MVVM Light, it has the similar class and other classes which help to use the MVVM pattern. For me it is easier to add reference to a library than to copy the code, but it is controversial question whether to use 3rd party libraries or to write your own.
-
Nicolas Fall over 8 yearsis the
/
in your{Binding CollectionView/}
on purpose? -
Mizipzor over 8 yearsYes, that makes it bind to the current item. Which when used with
IsSynchronizedWithCurrentItem
means the selected item. Here's a blog post. -
Julian Sievers over 8 yearsVery neat solution. Also didn't know about the forward slash binding. Sometimes I'm really astonished where people know this kind of things from. Thank you!
-
T.Y. Kucuk about 8 yearsThis is a good solution. But there is a drawback here. If one double clicks DataGrids' header, the command will be executed anyway. In some scenarios this might be undesirable thing for the developer. How can it be resolved that?
-
simonalexander2005 almost 8 yearsAs I understand it, you can use the "CanExecute" part of the ICommand implementation to determine whether the parameter passed is a valid one for running the command on
-
ProfK over 7 yearsWhen I use the forward slash on the parameter, it always passes the item in the first row. I do have
IsSynchronizedWithCurrentItem="True"
. The grid is bound to anObservableCollection
. Is there anything I'm missing re. the virtualisation? -
LukaszTaraszka over 6 yearsI give +1 but I think is hack anyway.
-
MaYaN over 6 yearsNice and elegant.
-
Dmitriy Nemykin over 5 yearsNote, that if
IsReadOnly="False"
for your DataGrid, then the first click may be stolen the selection mechanism. SetIsReadOnly="True"
to fix that up. -
Tyler B. Long almost 5 yearsPersonally I don't like the
Binding CollectionView/
. Got this to work if you give theDataGrid
a name and in the command parameter of the mouse binding do the following:CommandParameter="{Binding ElementName=SomeGridName, Path=SelectedItem}"
-
JMIII almost 4 yearsNice but there is an issue. Lets say you have a datagrid with multiple columns and the last column is not set to width=* and you double click to the far right in extra space after last column the selected item will not update and it will pass whatever the selected item was before. And if no selected item exists yet it will pass null.
-
Joe Huang about 3 yearsWhy so many black magic in WPF/XAML? Where's the doc to describe what is the slash?