Search code examples
.netwpfxamldatatemplateitemscontrol

How-to define Empty DataTemplate for the ItemsControl based controls like ListView or DataGrid


ASP.NET controls like ListView allows providing a custom template by setting the ListView.EmptyDataTemplate property, this template will be rendered in case of empty data source.

How to do the same in WPF (XAML only preferrable) for ItemsControl based controls like ListView and DataGrid? So I want to show my custom DataTemplate in case when ItemsSource is empty.


Solution

  • You can use set the Template property based on a DataTrigger

    For example,

    In Resources:

    <ControlTemplate x:Key="EmptyListBoxTemplate">
         <TextBlock Text="Items count == 0" />
    </ControlTemplate>
    

    Control itself:

    <ListBox ItemsSource="{Binding SomeCollection}">
        <ListBox.Style>
            <Style TargetType="{x:Type ListBox}">
                <Style.Triggers>
                    <DataTrigger Value="{x:Null}" Binding="{Binding DataContext.SomeCollection, RelativeSource={RelativeSource Self}}">
                        <Setter Property="Template" Value="{StaticResource EmptyListBoxTemplate}" />
                    </DataTrigger>
                    <DataTrigger Value="0" Binding="{Binding DataContext.SomeCollection.Count, RelativeSource={RelativeSource Self}}">
                        <Setter Property="Template" Value="{StaticResource EmptyListBoxTemplate}" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </ListBox.Style>
    </ListBox>
    

    There might be an simplier way of doing the binding, but I don't have a compiler on me right now to figure out what it would be :)