WPF - Remove focus when clicking outside of a textbox

前端 未结 13 2137
粉色の甜心
粉色の甜心 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:39

    Another way that worked for me was using

    Mouse.AddPreviewMouseDownOutsideCapturedElementHandler

    For example, say you had a TextBlock that when clicked, should become editable by showing a focused TextBox. Then when the user clicked outside the TextBox, it should be hidden again. Here's how you can do it:

    private void YourTextBlock_OnMouseDown(object sender, MouseButtonEventArgs e)
    {
        YourTextBox.Visibility = Visibility.Visible;
        YourTextBox.Focus();
        CaptureMouse();
        Mouse.AddPreviewMouseDownOutsideCapturedElementHandler(this, OnMouseDownOutsideElement);
    }
    
    private void OnMouseDownOutsideElement(object sender, MouseButtonEventArgs e)
    {
        Mouse.RemovePreviewMouseDownOutsideCapturedElementHandler(this, OnMouseDownOutsideElement);
        ReleaseMouseCapture();
        YourTextBox.Visibility = Visibility.Hidden;
    }
    
    0 讨论(0)
提交回复
热议问题