Add a brick to build Chinese knowledge base — The University of Science and Technology of China does not return

Problem description

When WPF adds TextBox input, it often expects it to take effect immediately by clicking outside the TextBox.

The native TextBox doesn’t seem to have this function, so we found a way to achieve this effect by forcing TextBox to lose focus.

I haven’t found a more elegant way yet.

The solution

  1. Add an invisible TextBox to receive focus and a MouseDown event to respond to mouse clicks.
<Window x:Class="Kavand.WpfTextBoxStyle.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <! -- Invisible TextBox -->
        <TextBox x:Name="FocusHolder" Width="0"/>
        <ScrollViewer MouseDown="UIElement_OnMouseDown">
            <StackPanel>
                <WrapPanel>
                    <TextBox Style="{DynamicResource SimpleTextBox}" Text="My text... Top"/>
                </WrapPanel>
                
                <! -- PlaceHolder -->
                <Canvas Height="300"></Canvas>
                <WrapPanel>
                    <TextBox Style="{DynamicResource SimpleTextBox}" Text="My text... Center"/>
                </WrapPanel>
                
                <! -- PlaceHolder -->
                <Canvas Height="300"></Canvas>
                <WrapPanel>
                    <TextBox Style="{DynamicResource SimpleTextBox}" Text="My text... Bottom"/>
                </WrapPanel>
            </StackPanel>
        </ScrollViewer>
    </Grid>
</Window>
Copy the code

Using the Grid layout avoids the page jumping to the FocusHolder when it gets focus in a long layout like ScrollViewer.

  1. The MouseDown event is triggered when the mouse clicks outside of the TextBox we are editing, in which we take the previous TextBox out of focus
    public partial class MainWindow {
        public MainWindow() {
            InitializeComponent();
        }

        private void UIElement_OnMouseDown(object sender, MouseButtonEventArgs e)
        {
            //FocusHolder takes focus out of the TextBox being editedFocusHolder.Focus(); }}Copy the code

The effect is as follows:

Refer to the article

  1. Textbox enforces losing focus in WPF
  2. WPF – How to remove focus from text box when external click?