【问题标题】:How to perform Single click checkbox selection in WPF DataGrid with IEditableObject object如何使用 IEditableObject 对象在 WPF DataGrid 中执行单击复选框选择
【发布时间】:2017-08-10 21:39:54
【问题描述】:
【问题讨论】:
标签:
c#
wpf
mvvm
datagrid
viewmodel
【解决方案1】:
您可以为DataGrid 处理GotFocus 事件并显式进入编辑模式并选中/取消选中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}" />
...
【解决方案2】:
对所有复选框使用相同的方法
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;
}
}
}