开发者

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, RoutedEvent开发者_开发技巧Args e)
    {
        Items.Add(_random.Next(100));
    }

    private readonly Random _random = new Random();
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜