WPF - Adding dynamic controls to dynamically added Tabitem?

25,251

Solution 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

Solution 2

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)

Share:
25,251

Related videos on Youtube

Paul Moss
Author by

Paul Moss

Updated on July 09, 2022

Comments

  • Paul Moss
    Paul Moss almost 2 years

    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

  • Paul Moss
    Paul Moss over 13 years
    Thank you, I am beginning to make some progress now. So if my usercontrol contains say several controls, are you saying that I can pass the data 'all in one go' to the TabItem by packaging up the data in an object? Presumably then the usecontrol could contain a method to do just that which I could call?
  • Aaron McIver
    Aaron McIver over 13 years
    @Paul In so many words yes. In your UserControl you can then make use of DataBinding, since when you set the DataContext of the TabItem it will cascade down. Then in the UserControl your controls can be bound to the data within the DataContext.
  • Paul Moss
    Paul Moss over 13 years
    Many thanks Aaron for all your help, just one more question, each tabitem is identical but I am not sure the best control(s) to use. On each tab I need to display 'rows' representing each row read from a database. Each row of data consists of 3 text fields, a boolean, and an integer in the range 1-4 representing one of 4 possible images. I need to display the text, the boolean value, (in a checkbox), and the corresponding image with some suitable control with which to change it. Could I do this somehow with a datagrid?
  • Aaron McIver
    Aaron McIver over 13 years
    @Paul Yes a DataGrid would be perfect for this, there are some stock columns as well as a template column which you can define as you see fit...blogs.msdn.com/b/vinsibal/archive/2008/08/19/…
  • Paul Moss
    Paul Moss over 13 years
    Thats fantastic Aaron, just what I needed, the best Xmas present!! Many thanks for all your help.
  • krs1
    krs1 over 13 years
    Moving from Forms to WPF, this really helped.

Related