1

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.

user3564895
  • 161
  • 6

1 Answers1

1

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.

Ahmad
  • 1,462
  • 15
  • 23
  • Thank you. My code is similar to http://stackoverflow.com/questions/17063014/tabcontrols-containing-different-user-controls-using-mvvm?rq=1 Although the problem is different. The program has 5 tabs, 4 of which I desire to set focus to a particular text box when that tab is selected. Is there a way to just listen for the view itself becoming active? How do I tell the Tab Control in the outer window to lose focus and give it to the v:OtherPageView? NB: Within OtherPageView I can use MVVM light messages to set the control, after the user has interacted with that view. – user3564895 Feb 01 '17 at 16:18
  • I am not sure i understand you well: Each time you click on a tab item the default behaviour of WPF tabcontrol is to recreate its contents view again -> the view can at this point in isolation of the TabControl attempts to take control of the focus using the above mentioned method I am not familiar with MVVM Light but you can use SelectionChanged event on the tab control and in its handler try to figure out with is the view used in the TabControl.Content property. – Ahmad Feb 01 '17 at 16:51
  • Code behind called from XAML (OtherPageView.xaml) IsVisibleChanged="UserControl_IsVisibleChanged" Then using http://stackoverflow.com/questions/3971179/wpf-tabcontrol-on-selectionchanged-set-focus-to-a-text-field for that page's xaml.cs (if visible) Despatcher.BeginInvoke (new Action(()=>{boxname.Focus(); })); and it works. – user3564895 Feb 02 '17 at 14:14