如何使用 IEditableObject 对象在 WPF DataGrid 中执行单击复选框选择
How to perform Single click checkbox selection in WPF DataGrid with IEditableObject object
DataGridCheckBoxColumn 的默认行为是用户必须单击两次才能更改复选框值。在 How to perform Single click checkbox selection in WPF DataGrid 主题中,有几个可行的解决方案,但存在一个问题 - 您在代码后面有一个 viewmodel 对象,它实现了 IEditableObject
接口,然后是 EndEdit
方法不执行。
知道如何使单击起作用并保留 IEditableObject
功能吗?
您可以处理 DataGrid
的 GotFocus
事件并显式进入编辑模式和 check/uncheck CheckBox
:
private void dg_GotFocus(object sender, RoutedEventArgs e)
{
DataGridCell cell = e.OriginalSource as DataGridCell;
if (cell != null && cell.Column is DataGridCheckBoxColumn)
{
dg.BeginEdit();
CheckBox chkBox = cell.Content as CheckBox;
if (chkBox != null)
{
chkBox.IsChecked = !chkBox.IsChecked;
}
}
}
<DataGrid x:Name="dg" AutoGenerateColumns="False" GotFocus="dg_GotFocus">
<DataGrid.Columns>
<DataGridCheckBoxColumn Binding="{Binding IsChecked, UpdateSourceTrigger=PropertyChanged}" />
...
对所有复选框使用相同的方法
private void GotFocus(object sender, RoutedEventArgs e)
{
var sen = sender as DataGrid;
DataGridCell cell = e.OriginalSource as DataGridCell;
if (cell != null && cell.Column is DataGridCheckBoxColumn)
{
sen.BeginEdit();
CheckBox chkBox = cell.Content as CheckBox;
if (chkBox != null)
{
chkBox.IsChecked = !chkBox.IsChecked;
}
}
}
DataGridCheckBoxColumn 的默认行为是用户必须单击两次才能更改复选框值。在 How to perform Single click checkbox selection in WPF DataGrid 主题中,有几个可行的解决方案,但存在一个问题 - 您在代码后面有一个 viewmodel 对象,它实现了 IEditableObject
接口,然后是 EndEdit
方法不执行。
知道如何使单击起作用并保留 IEditableObject
功能吗?
您可以处理 DataGrid
的 GotFocus
事件并显式进入编辑模式和 check/uncheck CheckBox
:
private void dg_GotFocus(object sender, RoutedEventArgs e)
{
DataGridCell cell = e.OriginalSource as DataGridCell;
if (cell != null && cell.Column is DataGridCheckBoxColumn)
{
dg.BeginEdit();
CheckBox chkBox = cell.Content as CheckBox;
if (chkBox != null)
{
chkBox.IsChecked = !chkBox.IsChecked;
}
}
}
<DataGrid x:Name="dg" AutoGenerateColumns="False" GotFocus="dg_GotFocus">
<DataGrid.Columns>
<DataGridCheckBoxColumn Binding="{Binding IsChecked, UpdateSourceTrigger=PropertyChanged}" />
...
对所有复选框使用相同的方法
private void GotFocus(object sender, RoutedEventArgs e)
{
var sen = sender as DataGrid;
DataGridCell cell = e.OriginalSource as DataGridCell;
if (cell != null && cell.Column is DataGridCheckBoxColumn)
{
sen.BeginEdit();
CheckBox chkBox = cell.Content as CheckBox;
if (chkBox != null)
{
chkBox.IsChecked = !chkBox.IsChecked;
}
}
}