#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).

Advertisements