如何影响WPF中的键盘焦点遍历策略?

时间:2016-06-17 16:38:15

标签: .net wpf focus

假设有两个WPF列表。 我希望能够使用键盘箭头键无缝迭代它们列出的项目。 默认情况下,焦点范围仅限于单个容器内的迭代。 有没有办法帮助它跨越集装箱边界?

2 个答案:

答案 0 :(得分:0)

所以说有两个ListView:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <ListView x:Name="list1" KeyDown="list1_KeyDown">
        <ListViewItem Content="item 1"/>
        <ListViewItem Content="item 2"/>
        <ListViewItem Content="item 3"/>
    </ListView>
    <ListView x:Name="list2" Grid.Row="1" KeyDown="list2_KeyDown">
        <ListViewItem Content="item 1"/>
        <ListViewItem Content="item 2"/>
        <ListViewItem Content="item 3"/>
    </ListView>
</Grid>

为KeyDown事件添加两个处理程序:

private void list1_KeyDown(object sender, KeyEventArgs e) {
    switch (e.Key) {
        // check for down key
        case Key.Down:
            // if the bottom item is selected
            if (list1.SelectedIndex == list1.Items.Count - 1) {
                // select the next item
                list2.SelectedIndex = 0;
                (list2.Items[0] as UIElement).Focus();
                // make sure nothing else happens
                e.Handled = true;
            }
            break;
    }
}

private void list2_KeyDown(object sender, KeyEventArgs e) {
    switch (e.Key) {
        // check for up key
        case Key.Up:
            // if the top item is selected
            if (list2.SelectedIndex == 0) {
                // select the previous item
                int i = list1.Items.Count - 1;
                list1.SelectedIndex = i;
                (list1.Items[i] as UIElement).Focus();
                // make sure nothing else happens
                e.Handled = true;
            }
            break;
    }
}

这将允许使用向上/向下键在两个ListView之间进行无缝垂直过渡。您可以添加更多案例块以添加其他左/右过渡或其他。 我确定您可以了解如何根据您的具体情况进行调整。

答案 1 :(得分:0)

刚想出来了。 KeyboardNavigation.DirectionalNavigation附加属性可以解决这个问题。 (可能的值列出here

样本可以简化为:

<StackPanel KeyboardNavigation.DirectionalNavigation="Contained">
  <ListBox KeyboardNavigation.DirectionalNavigation="Continue">
    <ListBoxItem Content="Item 1" />
    <ListBoxItem Content="Item 2" />
    <ListBoxItem Content="Item 3" />
  </ListBox>
  <ListBox KeyboardNavigation.DirectionalNavigation="Continue">
    <ListBoxItem Content="Item A" />
    <ListBoxItem Content="Item B" />
    <ListBoxItem Content="Item C" />
  </ListBox>
</StackPanel>
相关问题