Question: In a ReadOnly
DataGrid, how can we place multiple cells, in a selected row, in Edit mode?
In following ReadOnly
DataGrid, the btnEdit_Click
event (shown below) successfully places the FirstName
column cell of selected row in the edit mode. But I need both FirstName
and LastName
column cells in the edit mode. If I enclose the entire code of that event in a for loop
as for (int i=2; i <=3; i++){...}
only the last cell (LastName
) column gets the edit mode.
Remark:
- All other rows have to stay in
ReadOnly
mode when user is editing the selected row. - I'm using Entity Framework Core for db operations (e.g. MyDataGrid.ItemsSource = db.Customers.ToList(); etc) and
.NET Core 3.1
,VS2019
latest version. - No
MVVM
is involved. - This is a similar post but for a column (not for row).
- For brevity, only two columns are shown. Real scenario has more than two columns.
DataGrid:
<DataGrid x:Name="MyDataGrid" IsReadOnly="True" SelectionMode="Single" AutoGenerateColumns="False" Margin="0,25,0,0">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Edit">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button x:Name="btnEdit" Content="Edit" Click="btnEdit_Click"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="ID" Visibility="Collapsed" Binding="{Binding CustomerId}" />
<DataGridTextColumn Header="FirstName" Binding="{Binding FirstName}" />
<DataGridTextColumn Header="LastName" Binding="{Binding LastName}" />
</DataGrid.Columns>
</DataGrid>
Code:
private void btnEdit_Click(object sender, RoutedEventArgs e)
{
DataGridCell dataGridCell;
MyDataGrid.CurrentCell = new DataGridCellInfo((sender as Button).DataContext, MyDataGrid.Columns[2]);
var cellContent = MyDataGrid.CurrentCell.Column.GetCellContent(MyDataGrid.CurrentCell.Item);
if (cellContent != null)
{
dataGridCell = (DataGridCell)cellContent.Parent;
dataGridCell.IsEditing = true;
}
}