Simple Empty Template for ItemsControls

One of my favourite elements in WPF is the VisualBrush. It allows you to define content (i.e. XAML) and then use it where ever you can use a brush.

Using this brush we can easily define content for an ItemsControl when it has no items.
We set a datatrigger to watch the Items.Count and when it’s zero make the background whatever content you want. In this example I just whack in some text.
As such:

<ListBox Height="100" Width="100"   ItemsSource="{Binding ItemsToBind">
  <ListBox.Style>
    <Style TargetType="ListBox" >
      <Style.Triggers>
        <DataTrigger Binding="{Binding Items.Count, RelativeSource={RelativeSource Self}}" 
                     Value="0">
          <Setter Property="Background">
            <Setter.Value>
              <VisualBrush Stretch="None">
                <VisualBrush.Visual>
                   <TextBlock Text="No Items" />
                </VisualBrush.Visual>
              </VisualBrush>
            </Setter.Value>
          </Setter>
        </DataTrigger>
      </Style.Triggers>					
    </Style>
  </ListBox.Style>
</ListBox>
Advertisements

4 thoughts on “Simple Empty Template for ItemsControls

  1. Jack says:

    Fantastic help! Thanks.

  2. Josh says:

    This is awesome! I was having a little difficulty searching for a solution. Thanks!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: