以下是重现该问题的一些示例代码:
<StackPanel Width="100">
<ToggleButton Content="Test 1"/>
<ToggleButton Content="Test 2"/>
<ToggleButton Content="Test 3"/>
<StackPanel FocusManager.IsFocusScope="True">
<ToggleButton Content="Test 4"/>
<ToggleButton Content="Test 5"/>
<ToggleButton Content="Test 6"/>
</StackPanel>
</StackPanel>如果使用tab键切换ToggleButtons,前3个选项可以用空格键选中/取消选中,因为键盘焦点仍然停留在您更改的项目上。但是,如果您在焦点范围内的框4-6之间单击/Tab键并尝试通过空格键更改它们,则焦点将在该焦点范围外重置,并且后续的空格键按键将在焦点范围外执行。
如何防止在更改IsFocusScope=True所在部分中的数据时键盘焦点离开
发布于 2021-09-30 17:42:32
我发现这个行为是WPF的“故意”。这篇文章最好地解释了这一点:https://stackoverflow.com/a/4954794/302677
创建附加属性以实现自己的焦点范围处理的建议解决方案也在该链接中。
public static class FocusExtensions
{
private static bool SettingKeyboardFocus { get; set; }
public static bool GetIsEnhancedFocusScope(DependencyObject element) {
return (bool)element.GetValue(IsEnhancedFocusScopeProperty);
}
public static void SetIsEnhancedFocusScope(DependencyObject element, bool value) {
element.SetValue(IsEnhancedFocusScopeProperty, value);
}
public static readonly DependencyProperty IsEnhancedFocusScopeProperty =
DependencyProperty.RegisterAttached(
"IsEnhancedFocusScope",
typeof(bool),
typeof(FocusExtensions),
new UIPropertyMetadata(false, OnIsEnhancedFocusScopeChanged));
private static void OnIsEnhancedFocusScopeChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e) {
var item = depObj as UIElement;
if (item == null)
return;
if ((bool)e.NewValue) {
FocusManager.SetIsFocusScope(item, true);
item.GotKeyboardFocus += OnGotKeyboardFocus;
}
else {
FocusManager.SetIsFocusScope(item, false);
item.GotKeyboardFocus -= OnGotKeyboardFocus;
}
}
private static void OnGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) {
if (SettingKeyboardFocus) {
return;
}
var focusedElement = e.NewFocus as Visual;
for (var d = focusedElement; d != null; d = VisualTreeHelper.GetParent(d) as Visual) {
if (FocusManager.GetIsFocusScope(d)) {
SettingKeyboardFocus = true;
try {
d.SetValue(FocusManager.FocusedElementProperty, focusedElement);
}
finally {
SettingKeyboardFocus = false;
}
if (!(bool)d.GetValue(IsEnhancedFocusScopeProperty)) {
break;
}
}
}
}
}https://stackoverflow.com/questions/69349232
复制相似问题