Website Links

Wednesday, 3 September 2014

Custom Templates for ListBoxItems in WPF

Sometimes you may want a ListBox which has custom row templates, for example when you want to display an object in a ListBoxItem. Firstly, we wanted to ensure our ListBoxItem took up all the horizontal space available to them so that we could mock a grid. This is what ListBox.ItemContainerStyle and its inner xaml does. Secondly, we wanted to have 2 TextBlocks in our ListBoxItem, to do this we defined an ItemTemplate for our ListBoxItem which can be seen below in our ListBox.ItemTemplate xaml.


  <ListBox Name="guessListBox">
    <ListBox.ItemContainerStyle>
      <Style TargetType="ListBoxItem">
        <Setter Property="HorizontalContentAlignment" 
                Value="Stretch" />
      </Style>
    </ListBox.ItemContainerStyle>
    <ListBox.ItemTemplate>
      <DataTemplate>
        <Grid>
          <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
          </Grid.ColumnDefinitions>
          <TextBlock Text="{Binding SuppliedGuess}" />
          <TextBlock Grid.Column="1" 
                     DataContext="{Binding Word}"
                     Text="{Binding Name}" />
        </Grid>
      </DataTemplate>
    </ListBox.ItemTemplate>
  </ListBox>



We gave the ListBox a name so that we could easily set the ItemsSource of it, using guessListBox.ItemsSource = Guesses; Guesses is an ObservableCollection of Guess objects with the properties: string SuppliedGuess, Word Word, and several others which are not important for the purpose of our example. The Word object has the property string Name, and several others which are also not important for this tutorial.

You may notice that the first TextBlock has its Text attribute bound to SuppliedGuess, this means that the Text attribute automatically comes from a Guess's SuppliedGuess property as a collection of Guesses are supplied as the ListBox's ItemsSource.

However, for the second TextBlock it has a DataContext set. This is because the Text attribute automatically comes from the Name property of the Word which is a property of the ListBoxItem's Guess.

No comments:

Post a Comment