private void DG_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Delete)
{
if (MessageBox.Show(Putl.Properties.Resources.Messages_Delete, "", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
{
DG.CanUserDeleteRows = true;
}
else
{
DG.CanUserDeleteRows = false;
}
}
}
public static class GridCommands
{
public static readonly RoutedUICommand Delete =
new RoutedUICommand(
"Удалить строку",
"DeleteRow",
typeof (GridCommands),
new InputGestureCollection(new[] {new KeyGesture(Key.Delete)})
);
}
public class DeleteBinding : CommandBinding
{
public DeleteBinding()
{
Command = GridCommands.Delete;
CanExecute += DeleteBindingCanExecute;
Executed += DeleteBindingExecuted;
}
static void DeleteBindingExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (MessageBox.Show("Delete this?", "Delete this?", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
return;
ApplicationCommands.Delete.Execute(e.Parameter, (IInputElement)sender);
}
static void DeleteBindingCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = ApplicationCommands.Delete.CanExecute(e.Parameter, (IInputElement)sender);
}
}
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<DataGrid
Name="ItemsGrid"
ItemsSource="{Binding Items}">
<DataGrid.Columns>
<DataGridTextColumn
Binding="{Binding}"
Header="N"
Width="*"
IsReadOnly="True"/>
</DataGrid.Columns>
<DataGrid.CommandBindings>
<l:DeleteBinding />
</DataGrid.CommandBindings>
</DataGrid>
<Button
Grid.Row="1"
Padding="5"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Content="Delete Row"
Command="{x:Static l:GridCommands.Delete}"
CommandTarget="{Binding ElementName=ItemsGrid}" />
</Grid>