dotnet / wpf

WPF is a .NET Core UI framework for building Windows desktop applications.
MIT License
7.08k stars 1.17k forks source link

Data-bound TabControls don't select an initial tab item #3310

Open inosik opened 4 years ago

inosik commented 4 years ago

Tab controls with data-bound ItemsSource don't select an initial tab item, if the tab control is visible at program start. If the tab control becomes visible later, it properly selects the first tab item. This can be verified by moving the "Dummy" tab item from the repro sample before the "Repro" tab item.

Actual behavior:

2020-08-06_13-20-01

Expected behavior:

The inner tab control should automatically select the first item.

Minimal repro:

Tabs.zip

ryalanms commented 4 years ago

Thanks, @inosik. We will take a look.

anjali-wpf commented 1 year ago

In order to make it work, you need to make some changes in the code. In MainWindow.xaml while defining TabControl, add Loaded event as Loaded="TabControl_Loaded", find code snippet below :

<TabControl>
        <TabItem Header="Repro">
         <TabControl
           Margin="10"
            ItemsSource="{Binding Tabs}"
            SelectedItem="{Binding SelectedTab}" Loaded="TabControl_Loaded">
            <TabControl.ItemContainerStyle>
               <Style TargetType="{x:Type TabItem}">
                  <Setter Property="IsSelected" Value="{Binding IsSelected}" />
                  <Setter Property="Header" Value="{Binding Header}" />
               </Style>
            </TabControl.ItemContainerStyle>
         </TabControl>
      </TabItem>
</TabControl>

And in MainWindow.xaml.cs add the following code -

private void TabControl_Loaded(object sender, RoutedEventArgs e)
{
    var tabControl = (TabControl)sender;
    tabControl.SelectedIndex = 0;
}

Here you can provide any tab index.

inosik commented 1 year ago

@anjali-wpf Thanks for looking at this. Yes, this does work. As well as setting the view models SelectedTab property when constructing it. This still looks like a bug to me, because it works without any extra code when the "Repro" tab becomes visible later.