问题:如何在grep
DataGrid中以编辑模式在选定的行中放置多个单元格?
在随后的ReadOnly
DataGrid中,ReadOnly
事件(如下所示)成功地将所选行的btnEdit_Click
列单元格置于编辑模式。但是我需要在编辑模式下同时使用FirstName
和FirstName
列单元格。如果我将事件的整个代码都用LastName
括在for loop
中,那么只有最后一个单元格(for (int i=2; i <=3; i++){...}
)列才进入编辑模式。
备注:
LastName
模式。ReadOnly
,.NET Core 3.1
最新版本。VS2019
。DataGrid :
MVVM
代码:
<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>
答案 0 :(得分:1)
无论DataGrid的IsReadOnly
属性为True还是False,一次只能将一个单元格置于编辑模式。
如果要允许用户单击“编辑”按钮后编辑特定行的单元格,则可以参考以下代码:
XAML:
<DataGrid x:Name="MyDataGrid" SelectionMode="Single" IsReadOnly="True" AutoGenerateColumns="False" Margin="0,25,0,0"
SelectedCellsChanged="MyDataGrid_SelectedCellsChanged" SelectionUnit="Cell">
<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>
后面的代码:
private Customer _editableCustomer;
private void btnEdit_Click(object sender, RoutedEventArgs e)
{
_editableCustomer = (Customer)MyDataGrid.SelectedCells.First().Item;
}
private void MyDataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
if (e.AddedCells.First().Item == _editableCustomer)
GetDataGridCell(MyDataGrid.SelectedCells.First()).IsEditing = true;
}
public static DataGridCell GetDataGridCell(DataGridCellInfo cellInfo)
{
var cellContent = cellInfo.Column.GetCellContent(cellInfo.Item);
if (cellContent != null)
return (DataGridCell)cellContent.Parent;
return null;
}
但是,我个人不会这样做。我将DataGrid的IsReadOnly
属性设置为False,并为DataGrid的BeginningEdit
事件添加事件处理程序。然后,在用户编辑行之前,我可以在事件处理程序中做任何我想做的事情。