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

WPF Tutorials - Binding Validation Rules

Bindings are a major part of WPF, and a big part of what makes it quick to create user interfaces in. They can be a little wordy and hard to debug sometimes, but overall they are extremely useful. Hopefully, after today's tutorial, you will find them even more useful - because today we are going to talk about building validation rules right into your bindings. Yup, you heard right - bindings in WPF have built in support for validation, and a number of the common controls have built in ways for displaying validation errors. Today we are going to build a simple little WPF application that has a TextBox in which the user is supposed to enter an IP Address (a v4 address - I was lazy and didn't want to write a validator for ipv6 as well :P). Below you can see a screenshot of the the app in action: A valid IPv4 address An invalid IPv4 address So the first thing that we need to do to add validation to a binding is to create a validation ru...

WPF Tutorial - Command Bindings and Custom Commands

Well, today we are going to take a look at the other side of that - creating and using your own custom command and command bindings. First we will take a look at setting up our own bindings to existing commands, and then we will see how to create our own commands from scratch. So an important thing to know, in order for command binding to make sense, is that (like many things in WPF) commands bubble. So when a command is triggered, it bubbles up along the WPF element tree from its origin (the command target, which we talked about in the previous tutorial), looking for an element that recognizes and can handle the command. The way that you can set up an element to handle a command is by creating a command binding. This can be done in either XAML or the code behind code - and we are going to take a look at the XAML first. <Window x:Class = "CustomCommandTest.CommandWindow"     xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"     ...

WPF Tutorial - Using The Built-In Commands

One of the features that WPF has is actually a blast from the past - something that MFC used to have, but was never included in WinForms. This is the concept of Commands. Commands are somewhat like events in that they are based on actions in the user interface, a command can get triggered (just like an event). But unlike regular events like 'click', commands are built in a way that makes it very easy to expose the same functionality at multiple places in an interface, with very little code duplication. On of the very useful features of commands is the fact that you actually get an automatic form of two way communication between the interface elements and the command they are bound too. This is because a command is made up of two main elements - Execute and CanExecute . So unlike in the regular world of events, when an action becomes unavailable, you can just have the CanExecute part of the command return false - and everything hooked to that command becomes d...