22

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?

Luca Petrini
  • 1,695
  • 2
  • 28
  • 53

3 Answers3

42

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?

Luca Petrini
  • 1,695
  • 2
  • 28
  • 53
  • Was trying to solve this problem since this morning .... you saved my evening :-) Thanks so much!! – Cris Aug 04 '11 at 15:31
1

try

Keyboard.Focus(TextBlockInput);

see here for more details

Arsen Mkrtchyan
  • 49,896
  • 32
  • 148
  • 184
-1

Another possible workaround is instead of Visibility property use Opacity. In this case calling Focus() actually sets focus.

  • 1
    It is a bad advice: `Visilibity.Collapsed` is very different than `Opacity=0`. Logical/keyboard focus, mouse events firing, theming, everything is different. `Opacity`is about aesthetics, `Visibility` is about the visual tree. – Askolein Mar 09 '19 at 16:41
  • @Askolein As stated in my reply, it's a workaround, not a proper solution. – Pavels Ahmadulins Mar 10 '19 at 12:48