WPF - Adding dynamic controls to dynamically added

2020-08-17 17:22发布

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

3条回答
仙女界的扛把子
2楼-- · 2020-08-17 18:06

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)

查看更多
Luminary・发光体
3楼-- · 2020-08-17 18:17

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;
}
查看更多
一纸荒年 Trace。
4楼-- · 2020-08-17 18:21

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
查看更多
登录 后发表回答