Home > OS >  TabControl switches Tabs automatically because Button remains it's focus
TabControl switches Tabs automatically because Button remains it's focus

Time:10-02

I have the following TabControl:

<TabControl x:Name="Tabs">
  <TabItem x:Name="TabItem1" Header="TabItem1" />
  <TabItem x:Name="TabItem2" Header="TabItem2" />
</TabControl>

TabItem1 has a ToolBar with some buttons inside. TabItem2 doesn't have a toolbar.

Since upgrading .NET version from 4.6.1 to 4.8 I encounter the following behaviour:

  1. When TabItem1 is being selected by the user the first button inside the toolbar gets focus.
  2. When the user now selects TabItem2 it sometimes switches back to TabItem1. This seems to be because the first button in TabItem1 remains it's focus.

Why didn't this happen with .NET 4.6.1? Is there any way to avoid this issue?

CodePudding user response:

I found a workaround by using a global event handler for all TabItems. On event the first control in the TabItem (which is usually the header) is being focused.

private void Application_Startup(object sender, StartupEventArgs e)
{
  EventManager.RegisterClassHandler(typeof(TabItem), Selector.SelectedEvent, new RoutedEventHandler(TabItem_Selected));
}

private void TabItem_Selected(object sender, RoutedEventArgs e)
{
  TabItem item = e.Source as TabItem;
  item?.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
}

But I still wonder why I do encounter this weird behaviour ... it shouldn't be necessary at all to use this workaround.

  • Related