【问题标题】:How to set focus to selected cell of WPF datagrid by single-click?如何通过单击将焦点设置到 WPF 数据网格的选定单元格?
【发布时间】:2012-12-15 12:06:36
【问题描述】:

我正在使用 WPFDataGrid 控件,并希望通过单击将键盘焦点设置为选定的Cell。默认情况下,用户必须双击单元格才能开始编写。我试过代码是:

<Style TargetType="{x:Type DataGridCell}" x:Key="DataGridCellStyle">
   <Setter Property="IsTabStop" Value="True" />
   <Setter Property="Focusable" Value="True" />    
   <Style.Triggers>
      <Trigger Property="IsKeyboardFocusWithin" Value="True">
        <Setter Property="IsEditing" Value="True" />
      </Trigger>
   </Style.Triggers>
</Style>

当我点击一个单元格时,它会到达Editmode,我需要再次点击以设置键盘焦点并开始写作!

【问题讨论】:

  • 您需要仅 xaml 的解决方案吗?
  • 是的,它会很棒,但我也可以使用后面的代码。
  • 您可以处理鼠标点击事件,然后使用 VisualTreeHelper.HitTest 方法。然后遍历可视化树到 DataGridCell 并做你需要的。将焦点放在它上面,设置为 Selected 等等。
  • 我不知道如何将焦点放在它上面?!!我应该访问它的文本框吗?

标签: wpf wpfdatagrid


【解决方案1】:

我不确定这是否是一个不错的功能。您可能无法选择多个单元格。无论如何处理OnCurrentCellChanged事件

void DG1_OnCurrentCellChanged(object sender, SelectedCellsChangedEventArgs e)
{
    DataGrid dg=(Datagrid)sender;
    dg.BeginEdit();
}

BeginEdit() 导致 DataGridPreparingCellForEdit 事件发生,我认为您应该处理该事件:

private void dg_PreparingCellForEdit(object sender,  DataGridPreparingCellForEditEventArgs e)
{
TextBox tb = e.EditingElement as TextBox;
if (tb != null)
   {
       tb.Focus();
       //you can set caret position and ...
   }
}

你也可以处理BeginningEdit事件。

【讨论】:

  • @Ron : 谢谢,但它不起作用,我需要键盘关注TextBox!你自己检查了吗?
  • @raha,我编辑了我的答案。看看它是否有帮助。 (我认为你不应该在 @ 和名称之间放置空格)
  • 非常感谢,但我不知道要绑定PreparingCellForEdit,因为我使用的是MVVM?!(我必须访问Textbox,因为其他一些原因,比如SelectAll)
  • @Ron : 非常感谢,但我必须绑定 PreparingCellForEdit,但不知道如何绑定它!(我必须访问 Textbox 出于 SelectAll 等其他一些原因)
  • 你想处理这个事件吗?它类似于您处理任何事件时:例如dg.PreparingCellForEdit += dg_PreparingCellForEdit
猜你喜欢
  • 2011-03-26
  • 1970-01-01
  • 1970-01-01
  • 2011-01-29
  • 1970-01-01
  • 2014-05-03
  • 1970-01-01
  • 1970-01-01
  • 2015-05-22
相关资源
最近更新 更多