如何使DataGrid作为一个整体在焦点遍历与箭头键行选择单一停止

本文关键字:遍历 焦点 单一停 选择 行选 DataGrid 何使 一个 | 更新日期: 2023-09-27 18:15:27

我有一个Window上面有几个控件。其中一个是DataGrid。我想实现一些非默认的焦点遍历。即:

  • DataGrid是单个停止作为一个整体,而不是每一行。
  • DataGrid聚焦时,用户可以使用上下键在行中导航。
  • 不允许使用左键和右键在列之间导航。
  • 第一列(也是唯一与导航相关的列)的类型为DataGridHyperlinkColumn。当用户按空格键或回车键时,执行超链接。

现在我有以下代码:

<DataGrid x:Name="DocumentTemplatesGrid"
          Grid.Row="2"
          ItemsSource="{Binding Source={StaticResource DocumentTemplatesView}}"
          IsReadOnly="True"
          AutoGenerateColumns="False"
          SelectionUnit="FullRow"
          SelectionMode="Single"
          TabIndex="1"
          IsTabStop="True">
  <DataGrid.CellStyle>
    <Style TargetType="DataGridCell">
      <Setter Property="IsTabStop" Value="False"/>
    </Style>
  </DataGrid.CellStyle>
  <DataGrid.RowStyle>
    <Style TargetType="DataGridRow">
      <Setter Property="IsTabStop" Value="False"/>
    </Style>
  </DataGrid.RowStyle>
  <DataGrid.Columns>
    <DataGridHyperlinkColumn Header="Name"
                             Width="2*"
                             Binding="{Binding Name}"/>
    <DataGridTextColumn Header="Description"
                        Width="5*"
                        Binding="{Binding Description}"/>
    <DataGridTextColumn Header="Type"
                        Width="*"
                        Binding="{Binding Type}"/>
  </DataGrid.Columns>
</DataGrid>

不幸的是,它没有达到我的期望。你能解释一下如何做到这一点吗?

如何使DataGrid作为一个整体在焦点遍历与箭头键行选择单一停止

所以,我给你的建议是:

 <DataGrid x:Name="DocumentTemplatesGrid"
              Grid.Row="2"
              ItemsSource="{Binding Items}"
              IsReadOnly="True"
              AutoGenerateColumns="False"
              SelectionMode="Single"
              SelectionUnit="FullRow"
              TabIndex="1"
              IsTabStop="True"
              PreviewKeyDown="DocumentTemplatesGrid_PreviewKeyDown">
        <DataGrid.CellStyle>
            <Style TargetType="DataGridCell">
                <Setter Property="IsTabStop" Value="False"/>
                <Setter Property="BorderThickness" Value="0"/>
                <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
            </Style>
        </DataGrid.CellStyle>
        <DataGrid.RowStyle>
            <Style TargetType="DataGridRow">
                <Setter Property="IsTabStop" Value="False"/>
            </Style>
        </DataGrid.RowStyle>

我已经在DataGrid上添加了PreviewKeyDown事件,并且从每个单元格中删除了单元格选择。因此,它看起来就像选择只在行上。

在后面的代码中,这是用空格/Enter打开链接的:

private void DocumentTemplatesGrid_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
    {
        if (e.Key == System.Windows.Input.Key.Space || e.Key == System.Windows.Input.Key.Enter)
        {
            if (e.Source is DataGrid)
            {
                string navigationUri = ((e.Source as DataGrid).SelectedItem as Class).Name;
                Process.Start(navigationUri);
            }
            e.Handled = true;
        }
    }

希望这是你正在寻找的,或者至少是一些帮助。