Search code examples
c#wpftabcontroltabitem

How to create tabitem headers from itemsource/list in c# and WPF?


I am trying to create a header for tabitem when there is an observable collection from JSON file as shown in the code below.

// Deserialize the JSON array into a List<ModelClass>
List<Model> dataList = JsonConvert.DeserializeObject<List<Model>>(messagecontent);

// Convert List<ModelClass> to ObservableCollection<ModelClass>
ObservableCollection<Model> observableCollection = new ObservableCollection<Model>(dataList);

Dispatcher.Invoke(() =>
{
    TabitemSub.Items.Clear();
    TabitemSub.ItemsSource = observableCollection;

    foreach (var item in observableCollection)
    {
        TabItem tabitem = new TabItem();
        tabitem.Header = item.property1;
        TabitemSub.Items.Add(tabitem);
    } 
}

My Xaml:

<TabControl>
    <TabItem Header="TabitemMain">
        <TabControl x:Name="TabitemSub" Height="500" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Margin="5">
        </TabControl>
    </TabItem>

but every time I run the code instead of giving me a string of property1 I keep on getting the path of the model, like project.MVVM.Model.Model in each result of item. Why is that happening and how can I resolve this?

Thank you


Solution

  • Managed to get it to work, if I make the following changes:

    Dispatcher.Invoke(() =>
    {
        TabitemSub.Items.Clear();
    
        foreach (Model item in datalist)
        {
            TabItem tabitem = new TabItem();
            tabitem.Header = item.property1;
            TabitemSub.Items.Add(tabitem);
        } 
    }
    

    then it will create tabs for each property1 value.


    This should however be done without creating UI elements in code behind, by means of an ItemContainerStyle or the DisplayMemberPath property like

    <TabControl x:Name="TabitemSub" ...>
        <TabControl.ItemContainerStyle>
            <Style TargetType="TabItem">
                <Setter Property="Header" Value="{Binding property1}"/>
            </Style>
        </TabControl.ItemContainerStyle>
    </TabControl>
    

    or

    <TabControl x:Name="TabitemSub" DisplayMemberPath="property1" .../>
    

    and

    TabitemSub.ItemsSource = datalist;