标签:rsa add image ice traversal grid handle ati 模板
原文:WPF 键盘导航附加属性解决TreeView的Tab导航焦点问题
TreeView是默认对上下左右响应,或者是Ctrl+Tab。
如果单独用tab则是不起作用的。
如果使用一般treeview可以利用以下方式来让tab进行导航。
设置Treeview和TreeviewItem的KeyboardNavigation
treeview
<Setter Property="KeyboardNavigation.TabNavigation" Value="Local"/>
treeviewitem
<Setter Property="KeyboardNavigation.TabNavigation" Value="Local" />
其次是对treeviewitem模板内部的border设置Focusable
<Border x:Name="Bd" Focusable="True" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Grid.Column="1" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true">
<ContentPresenter x:Name="PART_Header" ContentSource="Header" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</Border>
如果还是进不去TreeViewItem的内部,还可以使用一下附加属性
public static readonly DependencyProperty TabProperty = DependencyProperty.RegisterAttached("Tab", typeof(bool), typeof(TabTest), new PropertyMetadata(new PropertyChangedCallback(OnValueChanged))); public static bool GetTab(DependencyObject d) => (bool)d.GetValue(TabProperty); public static void SetTab(DependencyObject d, bool value) => d.SetValue(TabProperty, value); private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d != null && ((bool)e.NewValue)) { (d as UIElement).Focusable = true; (d as UIElement).PreviewKeyDown += TabTest_PreviewKeyDown; } } private static void TabTest_PreviewKeyDown(object sender, KeyEventArgs e) { var Element = Keyboard.FocusedElement as UIElement; if (e.Key == Key.Tab) { e.Handled = true; if (!Element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Down))) { Element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); } } }
在TreeViewItem的内部使用即可
<ItemsPresenter x:Name="ItemsHost" local:TabTest.Tab="True" Grid.ColumnSpan="2" Grid.Column="1" Grid.Row="1" />
简单版本
<Style TargetType="TreeView"> <Setter Property="KeyboardNavigation.TabNavigation" Value="Local"/> </Style> <Style TargetType="TreeViewItem"> <Setter Property="KeyboardNavigation.TabNavigation" Value="Local"/> </Style>
WPF 键盘导航附加属性解决TreeView的Tab导航焦点问题
标签:rsa add image ice traversal grid handle ati 模板
原文地址:https://www.cnblogs.com/lonelyxmas/p/12833884.html