I have a WPF application that contains a datagrid. It is bound to my List object \"Orders\" shown below.
public class OrderBlock
{
public Settings setting;
private void DataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs eventArgs)
{
if (sender == null) return;
if (eventArgs.ButtonState != MouseButtonState.Pressed) return; //only react on pressed
var dataGrid = sender as DataGrid;
if (dataGrid == null || dataGrid.SelectedItems == null) return;
if (dataGrid.SelectedItems.Count == 1)
{
var simplePension = dataGrid.SelectedItem as ISimplePension;
if (simplePension != null)
{
DataFetcherHolder.DataFetcher.SelectPension(simplePension);
Execute(EditSelectedPensionFunction);
}
}
}
Instead of double-clicking on the cell you may double-click on the grid
<DataGrid.InputBindings>
<MouseBinding Gesture="LeftDoubleClick"
Command="{Binding Edit}"
CommandParameter="{Binding ElementName=UsersDataGrid, Path=SelectedItem}" />
</DataGrid.InputBindings>
In ViewModel
public ICommand Edit { get; private set; }
Edit = new RelayCommand(EditUser, x => _isAdmin);
private static void EditUser(object usr)
{
if (!(usr is User))
return;
new UserEditorViewModel(usr as User);
}
We can do this in two ways,
a) By using Dependency property b) By adding System.Windows.Interactivity.dll.
Usually I prefer second way.
step 1: Implement ICommand interface in your view model class file.
step 2: Define your Command,
public ICommand DoubleClickCommand
{
//Do your code
}
step 2: add the above said .dll into your corresponding solution's xaml file.
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
step 3: Inside the Datagrid tag, use the below code to implement InvokeCommandAction Class
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<i:InvokeCommandAction Command="DoubleClickCommand"/>
</i:EventTrigger>
<i:Interaction.Triggers>
That's it. Hope it helps you:)
I'v used the MouseDoubleClick:
private void DataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs eventArgs)
{
if (sender == null) return;
if (eventArgs.ButtonState != MouseButtonState.Pressed) return; //only react on pressed
var dataGrid = sender as DataGrid;
if (dataGrid == null || dataGrid.SelectedItems == null) return;
if (dataGrid.SelectedItems.Count == 1)
{
var simplePension = dataGrid.SelectedItem as ISimplePension;
if (simplePension != null)
{
DataFetcherHolder.DataFetcher.SelectPension(simplePension);
Execute(EditSelectedPensionFunction);
}
}
}
When you double-click a data grid, the row is also selected, so I simply find the selected item and use it.