user3564895
user3564895

Reputation: 171

How to set focus to a textbox in a View (User control) selected by a tab view

This is a MVVM WPF Question., c#. Within a Window I have a Tab control that looks like this

    <TabControl TabStripPlacement="Top" >
    <TabItem Style="{StaticResource Tabitemstyle}">
    <TabItem.Header>
    <Label Content="Home" Style="{StaticResource Tablablestyle}"/>
    </TabItem.Header>
    <v:HomePageView/>
    </TabItem>
    <TabItem ....
    <v:OtherPageView/>

The trick is that there exists a textbox within the 2nd tab item that I wish to have input focus when the user selects the 2nd tab.

I've tried a few solutions, but the closest one so far (using data trigger style, or focused element) almost works:

I can see that the cursor is intended to be within the text box, but it doesn't blink. It seems the focus is still on the tab control in the outside window, not the text box element in the view that is defined by OtherPageView.xaml. When I hit tab once, it is all ok, but this is what I am trying to relieve the users of having to do.

Upvotes: 1

Views: 924

Answers (1)

Ahmad
Ahmad

Reputation: 1524

I would use the code behind:

  • Listen to visibility changed event on the TabItem content (i.e., v:HomePageView)

  • Find the textbox UI element (you can simply give the textbox a name in the xaml and refer to it from code behind)

  • Next, set focus on the text box using the UIElement.Focus() method

  • Finally if the keyboard did not focus , then use the Keyboard.Focus(...) method to focus the keyboard on the textbox.

Upvotes: 1

Related Questions