【发布时间】:2016-06-17 16:38:15
【问题描述】:
假设有两个 WPF 列表。 我希望能够仅使用键盘箭头键无缝地遍历它列出的项目。 默认情况下,焦点范围仅限于单个容器内的迭代。 有什么办法可以帮助它跨越容器边界?
【问题讨论】:
假设有两个 WPF 列表。 我希望能够仅使用键盘箭头键无缝地遍历它列出的项目。 默认情况下,焦点范围仅限于单个容器内的迭代。 有什么办法可以帮助它跨越容器边界?
【问题讨论】:
所以说有两个 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 之间进行无缝垂直转换。您可以添加更多案例块以添加额外的左/右转换或其他任何内容。 我相信您可以弄清楚如何根据您的具体情况进行调整。
【讨论】:
刚刚想通了。 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>
【讨论】: