【问题标题】:How to find out if CheckBox was clicked on DataGrid.GotFocus()如何确定是否在 DataGrid.GotFocus() 上单击了 CheckBox
【发布时间】:2014-05-26 16:06:52
【问题描述】:

我正在尝试实现单击行为以在 DataGrid 列中设置 CheckBoxes。这可行,但我只想在光标位于复选框上方时切换 IsChecked 属性。目前,只要 DataGridCell 获得焦点,我就会切换。

我找不到确定鼠标光标是否在复选框上方的方法...

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);
            }
        }
    }
}

有什么想法我在这里做错了吗?

最好的问候 去吧

【问题讨论】:

    标签: c# wpf datagrid


    【解决方案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
      }
    }
    

    【讨论】:

    • 非常感谢您的建议。虽然我不明白为什么这应该有效,但我没有测试并且不能否认它可能有效。 :) 由于该列是在 CodeBehind 中创建的,因此它需要比您的示例显示的更多的努力。如果我没有找到我想要的东西,我会尝试的。再次感谢!
    【解决方案2】:

    我找到了我要找的东西:

    bool isMouseOver = checkBox.InputHitTest(Mouse.GetPosition((IInputElement) checkBox)) != null;
    

    这将返回null,当鼠标不在CheckBox上时,就这么简单。

    【讨论】:

      猜你喜欢
      • 2020-05-28
      • 1970-01-01
      • 2012-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多