Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show if ItemsControl.ItemsSource is null

Greetings,

I have a ItemsControl which template I changed to show a RadioButton for every object in the binded ItemsSource.

However the ItemsSource can be empty and when it is empty I'd like to show a default value. Something like "The binded list contains no items for you to select"...

One way I thought of is to set the ItemsControl.Visibility to Collapsed and have a TextBlock.Vsibility to Visible which shows the text.. But this would include a lot more data.

Is it possible to show a default value if the ItemsControl.ItemsSource is null?

like image 879
Theun Arbeider Avatar asked May 12 '11 11:05

Theun Arbeider


2 Answers

After creating this simple converter:

public class AnyItemsToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var collection = value as IEnumerable;
        if (collection == null)
            return Visibility.Collapsed;

        return collection.OfType<object>().Any() ? Visibility.Collapsed : Visibility.Visible;
    }

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

You can override the ItemsControl Template to suppor this using RelativeSource Binding.

<UserControl x:Class="SilverlightApplication1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:SilverlightApplication1">
    <UserControl.Resources>
        <local:AnyItemsToVisibilityConverter x:Key="AnyItemsToVisibilityConverter" />
    </UserControl.Resources>

    <Grid x:Name="LayoutRoot" Background="White">
        <ItemsControl>
            <ItemsControl.Template>
                <ControlTemplate TargetType="ItemsControl">
                    <Grid>
                        <TextBlock Text="No Items to Display" 
Visibility="{Binding Items, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource AnyItemsToVisibilityConverter}}" />
                        <ItemsPresenter />
                    </Grid>
                </ControlTemplate>     
            </ItemsControl.Template>
        </ItemsControl>
    </Grid>
</UserControl>
like image 75
bendewey Avatar answered Sep 27 '22 17:09

bendewey


If I understood correctly, I think you can solve your problem by creating an IValueConverter.

like image 33
Dummy01 Avatar answered Sep 27 '22 16:09

Dummy01