Recently Gustavo Guerra posted a question on StackOverflow.com stating that behaviour of TextBlock was different on Windows Phone 7 and Windows Phone 8. If the Text is empty, WP7 renders TextBlock with Height set to 0. On WP8, it occupies full height.
I replied back stating that he should consider using a Converter for the same. Of course I had a similar issue with Cineworld app. The screenshot shows ratings & review screen I implemented – its almost a copy of Windows Phone Store ratings & review.
what I noticed was that if user chose to not review it, the textbox would be fully render. So I did what I suggested Gustavo do. Created two converters – StringLengthInvisibilityConverter and StringLengthVisibilityConverter. Almost identical but doing the opposite thing.
public class StringLengthInvisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { string itemVal = value as String; if (String.IsNullOrWhiteSpace(itemVal)) return Visibility.Collapsed; else return Visibility.Visible; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } public class StringLengthVisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { string itemVal = value as String; if (String.IsNullOrWhiteSpace(itemVal)) return Visibility.Visible; else return Visibility.Collapsed; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } }
<TextBlock Text="{Binding Review}" Visibility="{Binding Review, Converter={StaticResource InvisibilityConverter}}" TextWrapping="Wrap" Style="{StaticResource PhoneTextNormalStyle}" Grid.Column="0" Grid.Row="1" Grid.ColumnSpan="2"/> <TextBlock Text="(rating only)" Visibility="{Binding Review, Converter={StaticResource VisibilityConverter}}" Foreground="{StaticResource PhoneSubtleBrush}" TextWrapping="Wrap" Style="{StaticResource PhoneTextNormalStyle}" Grid.Column="0" Grid.Row="1" Grid.ColumnSpan="2"/>
Now I know one of you clever person is going to tell me I could have just used one 😛 Let me tell you this:
- I thought of it
- I could have searched around
- Realised no one really cares
- Created two converters and got the job done 🙂
- Submitted update and nap time
.
Pingback: Converter to toggle visibility when content is empty
Pingback: Converter to toggle visibility when content is empty | Answer My Query
Pingback: Super Duper All in one VisibilityConverter for #wpdev | Invoke IT Limited