Search code examples
wpfbindingtabitem

Display Dynamic Number in WPF TabItem Header


I have a TabControl where every item contains a User Control called Timeline. This "Timeline" has a property called "Number" which changes during runtime.

I want to make the property "Number" to be displayed in the TabItem header. And i have really no idea how to do that to be honest.

My first thought is that i have to create a Custom Control that derives from the original TabItem Control and create a DependencyProperty or something with a custom ControlTemplate.

I feel that i'm pretty bad on explaining this...

An example: I Want to do something like the third image in the post on following url, but instead of the close-button, i want to display the property "Number" that dynamically changes during runtime!

http://geekswithblogs.net/kobush/archive/2007/04/08/closeabletabitem.aspx


Solution

  • If we have this class:

    public class MyItem : INotifyPropertyChanged
    {
        public string Title {get; set;}
    
        private int number;
        public int Number
        {
            get { return number; }
            set
            {
                 number= value;
                 OnPropertyChanged("Number");
            }
        }
    }
    

    We can bind the collection of items to TabControl:

    <TabControl ItemsSource="{Binding MyItems}">            
        <TabControl.ItemTemplate>
            <DataTemplate>                    
                <StackPanel Orientation="Horizontal">                            
                    <TextBlock Text="{Binding Title}"/>
                    <TextBlock Text="{Binding Number}"/>
                </StackPanel>                        
            </DataTemplate>
        </TabControl.ItemTemplate>
        <TabControl.ContentTemplate>
            <DataTemplate>
                <my:TimeLine Number="{Binding Number, Mode=TwoWay}" />
            </DataTemplate>
        </TabControl.ContentTemplate>
    </TabControl>