I have a simple DataGrid with the following column:
<DataGridTextColumn Header="Column" Binding="{Binding ColumnValue, Mode=TwoWay, UpdateSourceTrigger=LostFocus}">
<DataGridTextColumn.CellStyle>
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="IsEnabled" Value="{Binding IsColumnEnabled}" />
<Style.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Background" Value="Gray" />
<Setter Property="Foreground" Value="Transparent" />
</Trigger>
</Style.Triggers>
</Style>
</DataGridTextColumn.CellStyle>
</DataGridTextColumn>
Let's assume two rows, the second one is disabled. When I enter a value into the first cell and hit Enter
, the focus doesn't jump to the next cell (because it's disabled). The problem is, I cannot enter into edit mode again with doubleclick until the current cell is focused.
Is there any trick to avoid this?
CodePudding user response:
If you want to implement a custom behaviour for Enter key presses, you could override the OnKeyDown
method in a custom class:
public class CustomDataGrid : DataGrid
{
protected override void OnKeyDown(KeyEventArgs e)
{
if(e.Key == Key.Return)
{
var currentCell = CurrentCell;
base.OnKeyDown(e);
if (CurrentCell.Column.GetCellContent(CurrentCell.Item)?.Parent is DataGridCell cell && !cell.IsEnabled)
CurrentCell = currentCell;
}
else
{
base.OnKeyDown(e);
}
}
}
Don't forget to change the root element of the DataGrid
in your XAML:
<local:CustomerDataGrid ... />