Search code examples
wpflistboxdefaultwpfdatagridempty-list

Default Content for Empty Datagrid or Listbox in WPF


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


Solution

  • 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>