Default Content for Empty Datagrid or Listbox in WPF

146 views Asked by At

Does anyone know how to add default content to an empty datagrid or listbox? Such as "No Results Returned" or something along those lines.

2

There are 2 answers

1
d.moncada On BEST ANSWER

You can do something like this, where the ListBox is Hidden and an associated error Grid is displayed instead. The benefit of this approach is that it is a bit more flexible, as you have an entire Grid to use instead of a VisualBrush.

<Grid>
    <ListBox x:Name="MyListBox">
        <ListBox.Style>
            <Setter Property="Visibility" Value="Visible" />
            <Style TargetType="ListBox">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Items.Count, RelativeSource={RelativeSource Self}}" Value="0">
                        <Setter Property="Visibility" Value="Hidden" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </ListBox.Style>
    </ListBox>
    <Grid>
        <Grid.Style>
            <Style TargetType="Grid">
                <Setter Property="Visibility" Value="Hidden" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ElementName=MyListBox, Path=Items.Count}" Value="0">
                        <Setter Property="Visibility" Value="Visible" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        <Grid.Style>
        <TextBlock Text="No Results Returned" />
    </Grid>
<Grid>
0
Edd On
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Items.Count, RelativeSource={RelativeSource Self}}" Value="0">
                        <Setter Property="CanUserSortColumns" Value="False" />
                        <Setter Property="Background">
                            <Setter.Value>
                                <VisualBrush Stretch="None">
                                    <VisualBrush.Visual>
                                        <TextBlock Text="We did't find any matching records for your group..." FontSize="14" FontWeight="SemiBold" Foreground="LightCoral"/>
                                    </VisualBrush.Visual>
                                </VisualBrush>
                            </Setter.Value>
                        </Setter>
                    </DataTrigger>
                </Style.Triggers>

This is what I have found and was able to to test it. Thanks to anyone who tried to help.