K. Shah K. Shah - 1 month ago 8x
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">



2. C# File

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

tab.Header = glist.ItemGroup;
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;

I tried following options:

  1. By adding stackpanel, Grid, Button in

  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.


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.



The above is the change in XAML part.