Sunday, November 25, 2012

Converter to hide items when something is null or empty string

Often times in Xaml you've got some labels, or buttons that you don't want to show if something in the ViewModel is null or empty. Take the example below. The ViewModel has a nullable property rating. If it is non-null a handful of controls are rendered to show it graphically and numerically. If it is null however we don't want to see any of that stuff. This converter helps hide elements of something in the ViewModel is null or empty string.

<Grid Margin="30,0,0,0" Visibility="{Binding Location.rating, Converter={StaticResource NullToVisibilityConverter}}">
        <RowDefinition Height="Auto"></RowDefinition>
        <RowDefinition Height="Auto"></RowDefinition>
        <RowDefinition Height="*"></RowDefinition>
    <TextBlock Grid.Row="0" Text="Rating" VerticalAlignment="Center" HorizontalAlignment="Center" Style="{StaticResource BasicTextStyle}"/>
    <Grid Margin="0,15,0,0" Grid.Row="1" >
        <TextBlock Text="{Binding Location.rating}" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Center" VerticalAlignment="Center" TextAlignment="Center" FontSize="24"/>
            EndAngle="{Binding RatingAngle}"
            Fill="{Binding RatingColor}">
    <TextBlock Grid.Row="2" Text="{Binding Reviews}" Margin="0,15,0,0"  Style="{StaticResource BodyTextStyle}" 
               VerticalAlignment="Stretch" HorizontalAlignment="Stretch" TextAlignment="Center"/>

    public sealed class NullToVisibilityConverter : IValueConverter
        public object Convert(object value, Type targetType, object parameter, string language)
            if (value is string)
                return string.IsNullOrEmpty((string)value) ? Visibility.Collapsed : Visibility.Visible;

            return object.ReferenceEquals(value, null) ? Visibility.Collapsed : Visibility.Visible;

        public object ConvertBack(object value, Type targetType, object parameter, string language)
            throw new NotImplementedException();