我正在尝试实现单击行为以在DataGrid列中设置CheckBoxes。这有效,但我想只在光标位于Checkbox上方时切换IsChecked属性。目前,只要DataGridCell获得焦点,我就会切换。
我找不到确定鼠标光标是否在Checkbox上方的方法......
private void dataGridCell_GotFocus(object sender, RoutedEventArgs e)
{
DataGridCell focusedCell = e.OriginalSource as DataGridCell;
if (focusedCell != null)
{
DataGrid grd = (DataGrid)sender;
grd.BeginEdit(e);
Control editControl = focusedCell.Descendants<Control>().FirstOrDefault();
if (editControl != null)
{
CheckBox checkBox = editControl as CheckBox;
if (checkBox != null)
{
if (checkBox.IsEnabled)
{
checkBox.Focus();
checkBox.SetCurrentValue(ToggleButton.IsCheckedProperty, !checkBox.IsChecked);
var bindingExpression = checkBox.GetBindingExpression(CheckBox.IsCheckedProperty);
if (bindingExpression != null)
{
bindingExpression.UpdateSource();
}
}
}
else
{
dataGrid.Dispatcher.BeginInvoke(new Action(() => editControl.Focus()), DispatcherPriority.ContextIdle);
}
}
}
}
我在这里做错了什么想法?
祝你好运 Gope
答案 0 :(得分:1)
可能不是最优雅的方式,但这有效:
替换DataGridCheckBoxColumn
的原始模板:
<DataGridCheckBoxColumn.ElementStyle>
<Style TargetType="{x:Type CheckBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type CheckBox}">
<CheckBox IsChecked="{TemplateBinding IsChecked}"
VerticalAlignment="Center" HorizontalAlignment="Center" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</DataGridCheckBoxColumn.ElementStyle>
在你的事件处理程序中:
public void dataGridCell_GotFocus(object sender, RoutedEventArgs e)
{
if (e.OriginalSource is CheckBox)
{
// checkbox was clicked
}
else if (e.OriginalSource is DataGridCell)
{
// somwhere outside the checkbox was clicked
}
}
答案 1 :(得分:0)
我找到了我要找的东西:
bool isMouseOver = checkBox.InputHitTest(Mouse.GetPosition((IInputElement) checkBox)) != null;
当鼠标未在CheckBox上时,这将返回null,就像那样简单。