Skip to main content

WPF Tutorial - Binding to a TabControl

Here's a very basic scenario - you've got a collection of items and you'd like to display a tab for each one inside a TabControl. The TabControl exposes a property called ItemsSource, however setting up the templates to control how to display your data is not quite as straight forward as you might think.
The example data we're going to work with today are reviews for the movie Inception. First we need a class to represent a review.
/// <summary>
/// Class representing a single movie review.
/// </summary>
public class Review
{
  /// <summary>
  /// The name of the critic who provided the review.
  /// </summary>
  public string Critic { get; set; }

  /// <summary>
  /// A snippet of the critic's full review.
  /// </summary>
  public string ReviewSnippet { get; set; }

  /// <summary>
  /// Letter grade representing the review.  A-F.
  /// </summary>
  public string LetterGrade { get; set; }
}
All right, now that we've got an object let's populate the data. I'm pulling the reviews Yahoo! Movies.
public partial class MainWindow : Window
{
  public MainWindow()
  {
    InitializeComponent();

    // Create some reviews.
    var reviews = new List<Review>
    {
      new Review()
      {
        Critic = "Wesley Morris",
        LetterGrade = "B",
        ReviewSnippet = "For better and worse, it weighs nothing, " +
        "which is not the same as saying it means nothing."
      },

      new Review()
      {
        Critic = "Roger Ebert",
        LetterGrade = "A-",
        ReviewSnippet = "Like the hero of that film, the viewer " +
        "of Inception is adrift in time and experience."
      },

      new Review()
      {
        Critic = "Michael Phillips",
        LetterGrade = "B",
        ReviewSnippet = "Nolan conjures up a fever dream."
      }
    };

    // Set the ItemsSource of the TabControl
    // to the collection of reviews.
    _myTabControl.ItemsSource = reviews;
  }
}
All I did here was copy and paste Yahoo's review data into our new object. I then set the ItemsSource of the TabControl to the collection of reviews. The TabControl was added to my Window using XAML and the name was set to _myTabControl. If we compile and run it now, we won't get anything very helpful.
TabControl with no templates
In order to display our data in a meaningful way, we're going to have to specify two templates. One for the header (ItemTemplate) and one for the tab contents (ContentTemplate).
<Window x:Class="TabControlBinding.MainWindow"
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
       Title="MainWindow"
       Height="350"
       Width="525">
  <Grid>
    <TabControl x:Name="_myTabControl"
               Margin="10">

      <!-- Header -->
      <TabControl.ItemTemplate>
        <DataTemplate>
          <!-- Critic Name -->
          <TextBlock Text="{Binding Critic}" />
        </DataTemplate>
      </TabControl.ItemTemplate>

      <!-- Content -->
      <TabControl.ContentTemplate>
        <DataTemplate>
          <Grid Margin="5">
            <Grid.ColumnDefinitions>
              <ColumnDefinition Width="Auto" />
              <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
              <RowDefinition Height="Auto" />
              <RowDefinition Height="5" />
              <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>

            <!-- Grade -->
            <TextBlock Text="Grade: "
                      TextAlignment="Right" />
            <TextBlock Text="{Binding LetterGrade}"
                      Grid.Column="1" />

            <!-- Review Snippet -->
            <TextBlock Text="Review: "
                      TextAlignment="Right"
                      Grid.Row="2" />
            <TextBlock Text="{Binding ReviewSnippet}"
                      TextWrapping="Wrap"
                      Grid.Row="2"
                      Grid.Column="1" />

          </Grid>
        </DataTemplate>
      </TabControl.ContentTemplate>

    </TabControl>
  </Grid>
</Window>
Each tab's header now contains the name of the critic who provided the review. The contents of each tab contain the letter grade and the snippet. When we run this code, we now get something that works a little better.
TabControl with templates
That wraps up this tutorial. You now know how to quickly and easily populate a TabControl from a collection and customize its look and feel. If you have any questions or comments, feel free to leave them below.

Comments

Popular posts from this blog

create a table in SQL

To create a table, you can follow this formula: CREATE TABLE Country( Column1 , Column2 , Column3 ) or: CREATE TABLE Country( Column1 , Column2 , Column3 ); Each column is created as: ColumnName DataType Options Here is an example: CREATE TABLE Customers ( DrvLicNbr nvarchar(32), DateIssued DATE, DateExpired date, FullName nvarchar(50), Address NVARCHAR(120), City NvarChar(40), State NVarChar(50), PostalCode nvarchar(20), HomePhone nvarchar(20), OrganDonor BIT); GO To start from a sample code, open an empty Query window and display the Template Explorer. From the Template Explorer, expand Table. Drag Create Table and drop it in the Query window: -- ========================================= -- Create table template -- ========================================= USE <database, sysname, AdventureWorks> GO IF OBJECT_ID('<schema_name, sysname, dbo>.<table_name, sysname, sample_table>', 'U') IS NOT NULL DROP TABLE <schema_name, sysname, d...

Stored Procedures

Practical Learning: Introducing Stored Procedures Start Microsoft  SQL  Server  Management  Studio  and log in to your  server On the main menu, click File -> New -> Query With Current Connection To create a new database, copy and paste the following code in the Query window:   -- ============================================= -- Database: WattsALoan -- ============================================= USE master GO -- Drop the database if it already exists IF EXISTS ( SELECT name FROM sys.databases WHERE name = N'WattsALoan' ) DROP DATABASE WattsALoan GO CREATE DATABASE WattsALoan GO -- ========================================= -- Table: Employees -- ========================================= USE WattsALoan GO IF OBJECT_ID(N'dbo.Employees', N'U') IS NOT NULL DROP TABLE dbo.Employees GO CREATE TABLE dbo.Employees ( EmployeeID int identity(1,1) NOT NULL, EmployeeNumber nchar(10) NULL, FirstName nvarchar(20) NULL, LastName nvarcha...

Delete a table in SQL

To delete a table using SQL, use the following formula: DROP TABLE TableName The  DROP TABLE  expression is required and it is followed by the name of the undesired table. Here is an example: DROP TABLE Students; GO