更改为TabItem时关注

时间:2016-11-01 11:58:04

标签: c# wpf focus

我的窗口有TabControl和四个TabItem。当选择标签时,我需要将焦点更改为右textBox。这是一些正确的方法吗? 我尝试使用TabControl_SelectionChanged事件,但看起来它不起作用。

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

但如果我点击tab2焦点位于DataGrids的复选框列。

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>

1 个答案:

答案 0 :(得分:2)

您可以将它移动到XAML并让TabItem中的控件在准备就绪时移动焦点:

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