Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TabControl fails to create first tab when using data binding

I have a tab control which items source I databind to an observable collection. I use data templates to define the visual representation of the tab's headers and content.

When I add an item to the observable collection I get a tab header but no content. When I add a second item to the observable collection I get tab headers and content for both items. So first when the second item is added to the observable collection, the content for the first tab is created. Anyone knows if this is a bug or can explain why it happens? Is there a workaround? I tried using template selector with same result. Below is sample code to reproduce.

I tested this with both .NET 3.5 and 4.0.

XAML:

<Window x:Class="TabDemo.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="Window1" Height="300" Width="300">

    <StackPanel>
        <Button Content="Add new tabitem" Click="OnAdd" />

        <TabControl 
            ItemsSource="{Binding Path=Items}">
            <TabControl.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding}" />
                </DataTemplate>
            </TabControl.ItemTemplate>
            <TabControl.ContentTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding}" />
                </DataTemplate>
            </TabControl.ContentTemplate>
        </TabControl>
    </StackPanel>

</Window>

Code behind:

public partial class Window1
{
    public Window1()
    {
        InitializeComponent();

        Items = new ObservableCollection<int>(); 
        DataContext = this;
    }

    public ObservableCollection<int> Items { get; set; }

    private void OnAdd(object sender, RoutedEventArgs e)
    {
        Items.Add(_random.Next(100));
    }

    private readonly Random _random = new Random();
}
like image 983
Wallstreet Programmer Avatar asked Jun 09 '26 10:06

Wallstreet Programmer


1 Answers

If you set SelectedIndex="0" on your TabControl, it will work around this issue. I believe this has to do with a bug coercing the SelectedIndex as items are added/removed.

like image 199
CodeNaked Avatar answered Jun 12 '26 05:06

CodeNaked