Question

New to WPF, aware their are many questions on this already but none have worked. I would like a text box within a tab to get focus when the tab has been selected.

currently have

Private Sub TabControl1_Event(sender As Object, e As System.Windows.Controls.SelectionChangedEventArgs) 
_Handles TabControl1.SelectionChanged
    UpdateLayout()     'tried me.show() as well
    If TabControl1.SelectedIndex = 0 Then
        i = i + 1
        Title = "selected" + Convert.ToString(i)
        UserBox.Focus()
    End If
End Sub

the i increment and and title change are their just to see if the if loop is being entered and apparently it is, however the textbox (the only other control in the application) only gets focus when the program first starts.

As I said I have seen lots of the other questions similar to this here but either they are not exactly the same or just do not work. I am using vb.net in a WPF application. It seems like this should be very simple but cant for the life of me figure it out

It would be nice if this could be done via a tabItem event rather than a tabControl event also.

Update: IDK if it matters but I have seen others posting it and so this is my XAML

<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Burn In" Height="350" Width="525">
<TabControl Height="Auto" Name="TabControl1" Width="Auto">
    <TabItem Header="User" Name="UserTab">
        <Grid>
            <TextBox Height="25" HorizontalAlignment="Center" Margin="0" Name="UserBox" VerticalAlignment="Center" Width="250" AcceptsReturn="True" />
        </Grid>
    </TabItem>
    <TabItem Header="DUT" Name="DutTab">
        <Grid />
    </TabItem>
    <TabItem Header="Rack" Name="RackTab">
        <Grid />
    </TabItem>
    <TabItem Header="Programs" Name="ProgTab">
        <Grid />
    </TabItem>
</TabControl>
</Window>
Was it helpful?

Solution

I tested this code out on my computer and it worked fine.

Private Sub TabControl1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TabControl1.SelectedIndexChanged
        If TabControl1.SelectedIndex = 1 Then
            TabControl1.Update()
            TextBox1.Focus()
        End If
    End Sub

I declared the change of the Tab using the TabControl1_SelectedIndexChanged sub routine. If you do not clarify that the TabControl1 is changed you need to click in the TabPage for changes to take place.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top