简体   繁体   中英

How to set focus on an element of a user control?

I have a user control that has a TextBox on it. If I set focus on the TextBox in the constructor, then the TextBox works as expected. Sometimes though, I don't want the TextBox to have focus when the user control is first shown, and so I added a property to the user control which sets focus to the TextBox . This works, although I get the problem that I can't then reset focus on the TextBox after it has lost focus.

Doesn't anyone have any ideas why this might be happening?

    public ucQueryBox()
    {
        InitializeComponent();

        // Set default values for properties
        CodePrompt = "Barcode";
        TextBoxFontSize = 20;
        TextBoxMaxWidth = 0;
        Label = "";
        LabelFontSize = 20;
        LabelForeground = Colors.White.ToString();
        KeyboardButtonVisibility = Visibility.Visible;

        txtSelection.Focus();
    }

    /// <summary>
    /// Allows user to decide whether or the user control should have focus when it loads
    /// Focus puts the green boarder around the textbox
    /// </summary>
    [Browsable(true)]
    public Boolean SetFocusOnLoad
    {
        get { return _bSetFocusOnLoad; }
        set 
        { 
            _bSetFocusOnLoad = value;

            if (_bSetFocusOnLoad)
                txtSelection.Focus();
        }
    }

Focus in WPF is a complex topic. I think you'll find that the proper way to do what you want is to use FocusManager in your XAML:

<UserControl ... FocusManager.FocusedElement="{Binding ElementName=myTextBox}">
    <TextBox x:Name="myTextBox" />
</UserControl>

If you use FocusManager like this to establish all focus requirements (that is, you use FocusManager on all Windows and UserControls that have any sort of focus requirements), then you'll probably find that all the focusing works exactly like you expect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM