简体   繁体   中英

Focus when change to TabItem

I have window with TabControl and four TabItem s. And I need to change focus to right textBox when tab is selected. Is here some right way to do it? I tried to use TabControl_SelectionChanged event, but it looks like it doesn't work.

 private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
 {
     if (((TabItem)((TabControl)sender).SelectedItem).Name == "tab2")
     {
         UpdateLayout();
         textBox2EAN.Focus();
     }
     e.Handled = true;
 }

But if I click on tab2 focus is on DataGrids 's checkbox column.

TabItem: ...

<TabItem Name="tab2" Header="2" Width="50">
  <Grid>    
      <DataGrid Name="dataGrid" Margin="1" Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="3"
                VerticalAlignment="Stretch" HorizontalAlignment="Stretch" MouseDoubleClick="dataGrid_MouseDoubleClick"
                ItemsSource="{Binding RadkyDokladu.radky}" CanUserSortColumns="False" PreviewKeyDown="dataGrid_PreviewKeyDown"
                AutoGenerateColumns="False" IsReadOnly="True" FontSize="12" SelectionMode="Single" >
          <DataGrid.Columns>
              <DataGridCheckBoxColumn Header="" Binding="{Binding ZASKRTNUTO}" Width="auto" />
              <DataGridTextColumn Header="Náz" Binding="{Binding Artikl_NAME}" Width="*"/>
          </DataGrid.Columns>
      </DataGrid>
      <TextBox Name="textBox2EAN" Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" Margin="1" 
               VerticalContentAlignment="Center" />
  </Grid>
</Tabitem>

You can just move it to XAML and let the controls inside the TabItem move focus when they are ready:

<TabItem Name="tab2" Header="2" Width="50">
    <Grid FocusManager.FocusedElement="{Binding ElementName=textBox2EAN}">
       <DataGrid />
       <TextBox Name="textBox2EAN" />
   </Grid>
</TabItem>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM