views:

1262

answers:

1

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

+19  A: 

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>
Matt Hamilton
+1 looks good to me, I might have to use that one day.
bendewey
This works very nicely.
Scott A. Lawrence
I saw variants with data template selectors, but this one is without code-behind, brilliant!
levanovd
I just copy pasted it to clean new application and it doesn't work. I set listBox.ItemsSource = new List<string>() and nothing is displayed.
Martin Konicek
Ok, if you want it to work for every ListBox, remove the x:Key="ListStyle". Otherwise each ListBox has to specify that it uses this concrete named style.
Martin Konicek
Hey guys, is there a silverlight variation for this?
VoodooChild