调用CheckBox.Focus()时如何使CheckBox焦点边框出现?

时间:2011-03-23 03:24:37

标签: wpf checkbox focus border indicator

当用户选中CheckBox以使其聚焦时,CheckBox周围会出现一个虚线边框,表示它具有焦点。

当CheckBox通过调用myCheckBox.Focus()的代码聚焦时,不会出现这样的指示符(即使按空格键切换状态)。

当我以编程方式聚焦CheckBox时,如何使CheckBox焦点边框出现?

3 个答案:

答案 0 :(得分:8)

只有在您通过键盘导航时才会显示边框(Tab键)。关于此主题的MSDN page有更多详细信息:

  

焦点视觉风格仅在此时起作用   焦点行动是由   键盘。任何鼠标操作或   程序化焦点更改禁用   焦点视觉风格的模式。

如果要显示边框,可以使用IsFocused-属性上的触发器进行一些视觉更改(虽然您无法使用此设置边框)或者如果您确实需要边框,则必须创建自己的ControlTemplate。

在某个相关主题上还有一个thread here on SO,建议是模拟按键,但我建议不要将此解决方案用于您的问题。

答案 1 :(得分:0)

'initially set chkCheckBox.Appearance = 1

'on Got Focus set appearance = 0 - Flat
Private Sub chkCheckBox_GotFocus()
  chkCheckBox.Appearance = 0
End Sub

'on Lost Focus set appearance = 1 - 3D
Private Sub chkCheckBox_LostFocus()
  chkCheckBox.Appearance = 1
End Sub

答案 2 :(得分:0)

通过编辑KeyboardNavigationEx中的ControlzEx文件,我设法解决了这个问题(与往常一样,对punker76的贡献也很高)。

只需调用KeyboardHelper.Focus方法,并传递应该重点关注的UIElement(例如KeyboardHelper.Focus(myCheckBox)

这是KeyboardHelper类:

public sealed class KeyboardHelper
{
    private static KeyboardHelper _Instance;

    private readonly PropertyInfo _AlwaysShowFocusVisual;
    private readonly MethodInfo _ShowFocusVisual;

    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    static KeyboardHelper()
    {
    }

    private KeyboardHelper()
    {
        var type = typeof(KeyboardNavigation);

        _AlwaysShowFocusVisual = type.GetProperty("AlwaysShowFocusVisual", BindingFlags.NonPublic | BindingFlags.Static);
        _ShowFocusVisual = type.GetMethod("ShowFocusVisual", BindingFlags.NonPublic | BindingFlags.Static);
    }

    internal static KeyboardHelper Instance => _Instance ?? (_Instance = new KeyboardHelper());

    internal void ShowFocusVisualInternal()
    {
        _ShowFocusVisual.Invoke(null, null);
    }

    internal bool AlwaysShowFocusVisualInternal
    {
        get { return (bool)_AlwaysShowFocusVisual.GetValue(null, null); }
        set { _AlwaysShowFocusVisual.SetValue(null, value, null); }
    }

    public static void Focus(UIElement element)
    {
        element?.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
        {
            var keybHack = KeyboardHelper.Instance;
            var oldValue = keybHack.AlwaysShowFocusVisualInternal;

            keybHack.AlwaysShowFocusVisualInternal = true;

            try
            {
                Keyboard.Focus(element);
                keybHack.ShowFocusVisualInternal();
            }
            finally
            {
               keybHack.AlwaysShowFocusVisualInternal = oldValue;
            }
        }));
    }
}