问题描述
每当我尝试以编程方式移动焦点时,焦点视觉(虚线矩形)都不会显示.
Whenever I try to move focus programmatically the focus visual (the dotted rectangle) does not display.
如何强制显示此视觉对象?
What can be done to force this visual to display?
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="OnLoaded">
<StackPanel>
<TextBlock x:Name="a" Focusable="True">A</TextBlock>
<TextBlock Focusable="True">B</TextBlock>
<Button Focusable="False" Click="OnClick">Move Focus</Button>
</StackPanel>
</Window>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
Keyboard.Focus(a);
}
private void OnClick(object sender, RoutedEventArgs e)
{
var request = new TraversalRequest(FocusNavigationDirection.Next);
var elementWithFocus = Keyboard.FocusedElement as UIElement;
if (elementWithFocus != null)
elementWithFocus.MoveFocus(request);
}
}
推荐答案
如果您查看(在反射器/ilspy 中)KeyboardNavigation 的 ShowFocusVisual,您会发现框架仅在最后一个输入来自键盘时才会显示它(或者如果基于 KeyboardCues 系统参数信息的内部静态属性为真).所以我认为除了使用反射来临时设置该属性或异步聚焦元素并强制执行键盘操作(可能使用 winforms SendKeys 或 keybd_event api)之外,没有什么好的方法可以做到这一点,但我不推荐.
If you look (in reflector/ilspy) at the KeyboardNavigation's ShowFocusVisual you'll find that the framework will only show it if the last input was from the keyboard (or if an internal static property based on the KeyboardCues system parameter info is true). So I don't think there is a good way to do this short of using reflection to temporarily set that property or asynchronously focusing the element and forcing a keyboard action (maybe using the winforms SendKeys or keybd_event api) but I wouldn't recommend either.
这篇关于以编程方式导航焦点时未显示焦点视觉效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!