focus visual not showing when navigating focus pro

2019-02-18 19:09发布

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);
    }
}

1条回答
仙女界的扛把子
2楼-- · 2019-02-18 19:47

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.

查看更多
登录 后发表回答