As per 焦点管理器文档 -
逻辑焦点属于 FocusManager.FocusedElement 内
具体的重点范围。
So, its not necessary that element with logical focus will have keyboard focus as well
但反之亦然,即element with keyboard focus will surely have a logical focus as well.
如文档中所述FocusManager.FocusedElement guarantees logical focus and not keyboard focus
。所以你能做的就是创建一个attach behaviour
如同FocusManager.FocusedElement
这将set keyboard focus on an element
.
您可以参考此使用附加行为设置键盘焦点 -在 WPF 中设置键盘焦点.
该文章中的代码 -
namespace Invoices.Client.Wpf.Behaviors
{
using System.Windows;
using System.Windows.Input;
public static class KeyboardFocus
{
public static readonly DependencyProperty OnProperty;
public static void SetOn(UIElement element, FrameworkElement value)
{
element.SetValue(OnProperty, value);
}
public static FrameworkElement GetOn(UIElement element)
{
return (FrameworkElement)element.GetValue(OnProperty);
}
static KeyboardFocus()
{
OnProperty = DependencyProperty.RegisterAttached("On", typeof(FrameworkElement), typeof(KeyboardFocus), new PropertyMetadata(OnSetCallback));
}
private static void OnSetCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
var frameworkElement = (FrameworkElement)dependencyObject;
var target = GetOn(frameworkElement);
if (target == null)
return;
frameworkElement.Loaded += (s, e) => Keyboard.Focus(target);
}
}
}
在 XAML 中使用 -
<UserControl xmlns:behaviors="clr-namespace:Invoices.Client.Wpf.Behaviors">
<Grid behaviors:KeyboardFocus.On="{Binding ElementName=TextBoxToFocus}">
<TextBox x:Name="TextBoxToFocus" />
</Grid>
</UserControl>