WPF listbox empty datatemplate

.NetWpfListboxDatatemplate

.Net Problem Overview


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

.Net Solutions


Solution 1 - .Net

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>

Solution 2 - .Net

Based on @Matt Hamilton's accepted answer, for reference, I created a variation which does not require the binding, as it uses the HasItems property of the ListBox to trigger the empty template:

<ListBox.Style>
    <Style x:Key="EmptyListStyle"
           TargetType="ListBox"
           BasedOn="{StaticResource {x:Type ListBox}}">
        <Style.Triggers>
            <!-- Use ListBox.HasItems instead of Binding -->
            <Trigger Property="HasItems" Value="False">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate>
                            <TextBlock>No items to display</TextBlock>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Trigger>
        </Style.Triggers>
    </Style>
</ListBox.Style>

This allows the style to be used globally, without having to know the property name to which the list binds. I found it useful when binding to a CollectionViewSource defined in XAML.

I'm not aware of any drawbacks of this method, comments welcome if you should find any.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexView Question on Stackoverflow
Solution 1 - .NetMatt HamiltonView Answer on Stackoverflow
Solution 2 - .Netg tView Answer on Stackoverflow