WP7dev

Windows Phone 7 development tips

Null Visibility Converter

Needing to hide an object from a view when its binded data is empty is something quite common in WP7 development, to achieve this, a very simple way is to use this converter :

NullVisibilityConverter :


public class NullVisibilityConverter : IValueConverter

{

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

    {

        return value == null ? Visibility.Collapsed : Visibility.Visible;

    }

 

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

    {

        Visibility? v = value as Visibility?;

        return ((v.HasValue) || (v.Value == Visibility.Collapsed)) ? null : “”;

    }

}


Using this, you can bind your object Visibility to the value you want to check, and use the converter to hide it when it’s null :


<TextBlock Style=”{StaticResource ErrorMessageStyle}”

           Text=”{Binding CurrentErrorMessage}”

           Visibility=”{Binding CurrentErrorMessage, Converter={StaticResource

           NullVisibilityConverter}}”/>


This converter can also be adapted for Listbox to check whether its ItemsSource (List or ObservableCollection) is null or empty in order to hide the listbox and display something else

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: