#907 – Binding a TabControl to a List of Objects, part I

Instead of explicitly defining each tab of a TabControl in XAML, you can bind the TabControl to a list of objects, each tab representing an object in the list.

Suppose that we have a collection of Emperor objects, as follows:

public MainWindow()
{
this.InitializeComponent();
this.DataContext = this;

romanDudes = new ObservableCollection<Emperor>();
romanDudes.Add(new Emperor("Augustus", "27 BC", "14 AD", "Found bricks, left marble",
new Uri("Augustus.jpg", UriKind.Relative)));
// Add more dudes here
RaisePropertyChanged("RomanDudes");
}

private ObservableCollection<Emperor> romanDudes;
public ObservableCollection<Emperor> RomanDudes
{
get { return romanDudes; }
}

// INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged = delegate { };

private void RaisePropertyChanged(string propName)
{
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}

We set the ItemsSource of the TabControl to the list:

<TabControl Margin="5"
ItemsSource="{Binding RomanDudes}"/>

The TabControl now creates a tab for each Emperor object.
907-001
Both the Header and the Content for each TabItem defaults to the object’s string representation–the emperor’s name, in this case).

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

3 Responses to #907 – Binding a TabControl to a List of Objects, part I

  1. Pingback: Dew Drop – September 16, 2013 (#1,624) | Morning Dew

  2. Pingback: #908 – Binding a TabControl to a List of Objects, part II | 2,000 Things You Should Know About WPF

  3. Pingback: #909 – Binding a TabControl to a List of Objects, part III | 2,000 Things You Should Know About WPF

Leave a comment