K. Shah K. Shah - 3 months ago 21
C# Question

How to add TabControl content as button dynamically?

I am working on a project where I want to add button in content property of TabControl in WPF.

I tried lot many ways but I failed.

This is the code Example :


  1. XAML File

  2. c# File



1. XAML File

<TabControl TabStripPlacement="Left" Name="DynamicTab">
<TabControl.ItemTemplate>
<DataTemplate>

</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>

</DataTemplate>
</TabControl.ContentTemplate>


2. C# File

foreach(DataContextClass glist in groupsList)
{
TabItem tab = new TabItem();
StackPanel sp = new StackPanel();

tab.Header = glist.ItemGroup;
DynamicTab.Items.Add(tab);
itemsList = itemsDALObj.ItemsGroupWise(glist.ItemGroup);
for(int i =0 ; i<itemsList.Count;i++)
{
Button b = new Button();
b.Name = "Button" + (i + 1);
b.Content = itemsList[i].ItemName;
b.Height = 80;
b.Width = 100;
tab.Content = sp;
sp.Children.Add(b);
}
};


I tried following options:


  1. By adding stackpanel, Grid, Button in
    <DataTemplate>
    of
    <TabControl.ContentTemplate>
    .

  2. By adding Dynamic Grid and in that Grid I add Dynamic Button.

  3. Many other ways also which I am not able to explain.


Answer

You have to replace in XAML instead of <TabControl.ContentTemplate> replace it with <TabControl.DataContext> and that's the solution it takes me hours to find this little mistake.

<TabControl.DataContext>
     <DataTemplate>

     </DataTemplate>
</TabControl.DataContext>

The above is the change in XAML part.

Comments