Alvin
Alvin

Reputation: 8499

Prompt a message when datagrid is empty

I am using WPF. I am using datagrid to dynamically add items in it.

When the application is initially loaded, the datagrid is empty, or when all the items in the datagrid are remove, it only shows datagrid header.

How can I remove the header, and show a message like "Please insert an item." when the datagrid is empty.

Upvotes: 0

Views: 270

Answers (1)

McGarnagle
McGarnagle

Reputation: 102753

I'd use an IValueConverter for this. Bind directly to the Items source, and when it's null/empty, then return Visibility.Collapsed. Add text notice as a TextBlock, and negate the converter using a parameter.

<TextBlock Text="There are no items" 
    Visibility="{Binding Items,
        Converter={StaticResource ItemsToVisibilityConverter},ConverterParameter=negate}" />
<DataGrid Visibility="{Binding Items,
        Converter={StaticResource ItemsToVisibilityConverter}}">
</DataGrid>

And the converter has to make use of the ConverterParameter:

public class ItemsToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var items = value as IEnumerable<object>;
        bool isVisible = items != null && items.Count() > 0;
        if ((string)parameter == "negate") isVisible = !isVisible;
        return isVisible ? Visibility.Visible : Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Upvotes: 2

Related Questions