1
votes

In my WinRT/Phone 8.1 app I have a form with a number of Grids (serving as wrappers) each containing two or more TextBlocks. I want to show only data that is available, meaning that if the content TextBlock of a particular Grid is empty I want to hide the entire Grid.

For instance:ยด

<Grid x:Name="NameSection">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <TextBlock Grid.Row="0"
               x:Name="NameLabel"
               Text="Name:" />
    <TextBlock Grid.Row="1"
               x:Name="Name"
               Text="{Binding Name}" />
</Grid>

If the Name TextBlock is empty, the entire Grid's visibility should be collapsed.

Adding logic for this either to code behind or (worse) the ViewModel could get messy for this long form, so I wonder if I can achieve this using XAML and styles. How can it be done in WinRT? Can I style the Grid such that it's visibility is based on the content in one of its subviews?

1

1 Answers

1
votes

Converter

public class NullToVisibilityConverter: IValueConverter
{
   public object Convert(object value, Type targetType, object parameter, string language)
        {
            return value == null ? Visibility.Collapsed: Visibility.Visible;
        }

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

then use it like this

<Grid x:Name="NameSection" Visibility={Binding Name, Converter={StaticResource MyNullConverter}}>

edit: you can add string.IsNullOrEmpty(value as string) insted of value == null, if you want to check empty strings as well