我有一个跟随xaml的窗口:
<Window x:Class="TestDemoApp.TreeViewWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TreeViewWindow" Height="300" Width="300">
<Window.Resources>
<Style TargetType="Control" x:Key="FocusedStyle">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<Rectangle StrokeThickness="1"
Stroke="Red"
StrokeDashArray="1 2 3 4"
SnapsToDevicePixels="true"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="TreeViewItem">
<Setter Property="IsTabStop" Value="True"/>
<Setter Property="Focusable" Value="True"/>
<Setter Property="FocusVisualStyle" Value="{StaticResource FocusedStyle}"/>
<Setter Property="KeyboardNavigation.TabNavigation" Value="Continue"/>
</Style>
<Style TargetType="ListViewItem">
<Setter Property="IsTabStop" Value="True"/>
<Setter Property="Focusable" Value="True"/>
<Setter Property="FocusVisualStyle" Value="{StaticResource FocusedStyle}"/>
<Setter Property="KeyboardNavigation.TabNavigation" Value="Continue"/>
</Style>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<ListView TabIndex="1" BorderThickness="5" Focusable="True" IsTabStop="True" KeyboardNavigation.TabNavigation="Continue" FocusVisualStyle="{StaticResource FocusedStyle}">
<ListViewItem TabIndex="2" Content="List Item 1"/>
<ListViewItem TabIndex="3" Content="List Item 2"/>
</ListView>
<TreeView TabIndex="6" BorderThickness="5" Focusable="True" IsTabStop="True" KeyboardNavigation.TabNavigation="Continue" Grid.Row="1" FocusVisualStyle="{StaticResource FocusedStyle}">
<TreeView.Items>
<TreeViewItem TabIndex="7" Header="Tree Item 1">
<TreeViewItem Header="Tree Item 11"></TreeViewItem>
<TreeViewItem Header="Tree Item 12"/>
</TreeViewItem>
<TreeViewItem Header="Tree Item 2">
</TreeViewItem>
</TreeView.Items>
</TreeView>
</Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)
当我运行程序时,Tab键顺序是:
1. List View 2. List Item 1 3. List Item 2 4. Tree View 5. Tree Item 1 6. Tree Item 2 7. List View (#1) 8. List Item 1 (#2) 9. List Item 2 (#3) 10. Tree Item 2 (6#) 11+ Repeat #7 - #10
预期的行为是在进一步迭代时它会从#1到#6重复,但是它会在任何后续迭代中跳过#4和#5.
为什么是这样?我该如何解决?
哇,这太丑了。在很多方面,WPF 树视图都是我最喜欢的这个形容词的目标,但我以前没有遇到过这个特定的问题。
Continue我认为你不能比for做得更好KeyboardNavigation.TabNavigation,唯一的其他可能性是Local,但这也不起作用。请参阅这篇 msdn 文章。Cycle此外,项目和控件上的组合Continue并没有产生我想要的结果。
很明显,当焦点返回到列表视图时,所选项目将保留在树视图中,并且当树视图下次接收焦点时,它将焦点直接传递到先前选择的项目(树项目2),与列表视图不同,它保留选择,但首先正确地聚焦控件,然后是项目。
因此,一个可能对您有用的快速而肮脏的技巧是,当树视图失去焦点时从树视图中删除选择。不幸的是,每次所选项目发生更改时都会触发该事件,但黑客仍然有效。
<TreeView (...) LostFocus="TreeView_LostFocus">
Run Code Online (Sandbox Code Playgroud)
后面的代码:
private void TreeView_LostFocus(object sender, RoutedEventArgs e)
{
TreeView tv = (TreeView)sender;
TreeViewItem item = tv.SelectedItem as TreeViewItem;
if (item != null)
item.IsSelected = false;
}
Run Code Online (Sandbox Code Playgroud)