views:

724

answers:

1

I have a tabcontrol in WPF When I switch to a specific tabItem , I want to set the focus on a specific textBox

I added the code of textBox_n.Focus(); in the event handler of selectionChanged, but it didn't work.

I added the code in the event handler of the tabItem's GotFocus, but funny enough calling textBox_n.Focus(), was calling the tabItem's GotFocus again.

so where and what the best place to put it.

A: 

If you're using a grid to arrange the textboxes, you could put the grid you want to focus as the first child of the grid, and specify it's row and column to be the second or third, here's an example.

 <TabControl>
  <TabItem Header="Tab 1">

  </TabItem>
  <TabItem Header="Tab 2">
   <Grid>
    <Grid.RowDefinitions>
     <RowDefinition Height="Auto" />
     <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <TextBox Grid.Row="1" Margin="5">textBox2</TextBox> <!-- This textbox is the first child of the grid, so it gets focused -->
    <TextBox Grid.Row="0" Margin="5">textBox1</TextBox> <!-- This textbox is catually on top of textBox2 -->
   </Grid>
  </TabItem>
 </TabControl>

Not very elegant of course, but it gets the job done fast. Also no code-behind required.

Carlo