Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Focus on TextBox when UserControl change Visibility

I have a usercontrol loaded inside a canvas; this usercontrol on default have visibility collapsed. When a specific textbox of my window is focused the usercontrol become visible.

When usercontrol become visible I want set focus to another textbox inside usercontrol.

I try to do that:

private void UserControl_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
        if (this.Visibility == Visibility.Visible)
        {                
            FocusManager.SetFocusedElement(this, TextBlockInput);
        }
}

It seems work but there is a problem: the textbox seems focused but the cursor into textbox don't blink and I can't type chars for input.

I would that after focus the textbox is ready for input. How can I do?

like image 561
Luca Petrini Avatar asked Jun 24 '10 10:06

Luca Petrini


2 Answers

Well, I solve in this way:

private void UserControl_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    if (this.Visibility == Visibility.Visible)
    {
        this.Dispatcher.BeginInvoke((Action)delegate
        {
            Keyboard.Focus(TextBlockInput);
        }, DispatcherPriority.Render);
    }
}

I think that the problem was tha focus call into IsVisibleChanged event "scope"...right?

like image 73
Luca Petrini Avatar answered Sep 28 '22 03:09

Luca Petrini


try

Keyboard.Focus(TextBlockInput);

see here for more details

like image 36
Arsen Mkrtchyan Avatar answered Sep 28 '22 04:09

Arsen Mkrtchyan