WPF - Remove focus when clicking outside of a textbox

前端 未结 13 2136
粉色の甜心
粉色の甜心 2020-12-02 19:11

I have some textboxes where I would like focus to behave a little differently than normal for a WPF application. Basically, I would like them to behave more like a textbox b

相关标签:
13条回答
  • 2020-12-02 19:26

    you cant explicitly loose the focus of a control

    you can set the focus to other control instead

    **txt.Focusable=true;
    label.focus();
    Keyboard.Focus(txtPassword);**
    

    try this

    0 讨论(0)
  • 2020-12-02 19:34

    I was running into a similar issue, but when I wrapped a ScrollViewer control around my textboxes , all the textboxes would automatically lose focus when clicking anywhere outside the texboxes.

    0 讨论(0)
  • 2020-12-02 19:35

    I think, better way to solve this problem is adding MouseDown event handler to window with code behind:

    private void window_MouseDown(object sender, MouseButtonEventArgs e)
    {
        Keyboard.ClearFocus();
    }
    
    0 讨论(0)
  • 2020-12-02 19:35

    I'm not 100% sure, but if you set Focusable to true on the container element (Grid, StackPanel, etc) then it should take the focus away from the text box.

    0 讨论(0)
  • 2020-12-02 19:36

    You can use the IsKeyboardFocusedChanged event:

    myTextBox.IsKeyboardFocusedChanged += myTextBox_IsKeyboardFocusedChanged;
    
    private void SendFileCaptionTextBox_IsKeyboardFocusedChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        if (e.NewValue.ToString() == "True")
        {
            // it's focused
        }
        else
        {
            // it's not focused
        }
    }    
    
    0 讨论(0)
  • 2020-12-02 19:38

    You can register the PreviewMouseLeftButtonDownEvent to every type of element in App.xaml.cs on application startup.

    EventManager.RegisterClassHandler(typeof(UIElement), UIElement.PreviewMouseLeftButtonDownEvent,
                    new MouseButtonEventHandler(FocusElement));
    
    private void FocusElement(object sender, MouseButtonEventArgs e)
    {
         var parent = e.OriginalSource as DependencyObject;
         if (parent is UIElement element && !element.Focusable)
         {
             element.Focusable = true;
             element.Focus();
             element.Focusable = false;
         }
    }
    
    0 讨论(0)
提交回复
热议问题