我正在尝试在 WPF MVVM 中创建一个数据网格,其中包含带有信息的行,而 Columns 是一个DataGridCheckBoxColumn
代表Boolean
属性。
我希望能够单击一个复选框并一键将其更改为“已选中”。我还想禁用选择行的选项,并禁用更改其他列中其他内容的选项。
请指教。
使用这个答案作为起点:How to perform Single click checkbox selection in WPF DataGrid?
我做了一些修改并结束了这个:
WPF:
<DataGrid.Resources>
<Style TargetType="{x:Type DataGridRow}">
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="DataGridRow_PreviewMouseLeftButtonDown"/>
</Style>
<Style TargetType="{x:Type DataGridCell}">
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="DataGridCell_PreviewMouseLeftButtonDown"/>
</Style>
</DataGrid.Resources>
后面的代码:
private void DataGridRow_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
DataGridRow row = sender as DataGridRow;
if (row == null) return;
if (row.IsEditing) return;
if (!row.IsSelected) row.IsSelected = true; // you can't select a single cell in full row select mode, so instead we have to select the whole row
}
private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
DataGridCell cell = sender as DataGridCell;
if (cell == null) return;
if (cell.IsEditing) return;
if (!cell.IsFocused) cell.Focus(); // you CAN focus on a single cell in full row select mode, and in fact you HAVE to if you want single click editing.
//if (!cell.IsSelected) cell.IsSelected = true; --> can't do this with full row select. You HAVE to do this for single cell selection mode.
}
试试看,看看它是否符合您的要求。
DataGridCheckBoxColumn 默认以这种方式工作。第一次单击选择行或单元格,第二次单击更改复选框状态。有时需要:例如,当您需要在使用复选框之前调用选择更改事件时。为了创建一个复选框列,其中复选框在第一次单击时更改,最好使用 DataGridTemplateColumn 和 CheckBox 作为单元格模板:
<DataGridTemplateColumn Header="ChBoxColumn">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked" HorizontalAlignment="Center" VerticalAlignment="Center"></CheckBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>