WPF - Adding dynamic controls to dynamically added

2020-08-17 17:47发布

问题:

I am dynamically adding Tabitems to a Tab Control at runtime (in C#) and that works OK, but how can I then dynamically add controls to the new Tabitems? The Tabitems need to be dynamic because they depends on how many rows of data are read from a database. The layout of each Tabitem will be identical. Thanks

回答1:

If each TabItem is going to have the same layout I would simply create a UserControl which encompasses what you need from a layout and control stance and then place that within the TabItem.Content property.

You could then pass the data via object representation to the TabItem.DataContext property to initiate and make use of binding.

TabItem item = new TabItem();
item.Content = new CustomUserControl();
item.DataContext = data; //where data is the data that 
                         //comes from the database 
                         //being represented in object form


回答2:

Use the Content property of the new TabItem, there you can set anything, like strings or other WPF controls:

private void AddChildControl(TabItem tabItem)
{
    StackPanel newChild = new StackPanel();
    tabItem.Content = newChild;
}


回答3:

The TabItem is a content control, so just set its Content property to be any type of element you wish to display (e.g. a Grid containing other elements etc)