WPF listbox empty datatemplate

Alex picture Alex · Mar 31, 2009 · Viewed 17.2k times · Source

I was wondering how people handle a ListBox control that has no items? e.g. I want to bind a list of search results but if no results are found i would like to display "No results found".

The way i currently tackle this is that i hide the listbox if the result set count = 0 and show a label with the "No results found" message. Ideally i would like something like the ASP .NET datagrid EmptyTemplate solution.

Cheers

Answer

Matt Hamilton picture Matt Hamilton · Mar 31, 2009

I've had some success with this code:

<Style TargetType="ListBox" x:Key="ListStyle" BasedOn="{StaticResource {x:Type ListBox}}">
    <Style.Triggers>
        <DataTrigger 
            Binding="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=Items.Count}" 
            Value="0"
            >
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate>
                        <TextBlock>No items to display</TextBlock>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </DataTrigger>
    </Style.Triggers>
</Style>