Tags: , | Categories: Articles, Tutorials Posted by RTomlinson on 2/11/2011 11:02 PM | Comments (0)

Very simple one here, but one that may not seem completely obvious to those new to Silverlight.

The Scenario

A very common scenario in Silverlight is to databing the visibility of a control to a boolean value in your code. At first you may think you can just do inline binding as normal:

<Image Source="AnImage.png" Visibility="{Binding Accepted}" />

 

Today I was trying to do similar with a new project I'm working on. A StackExchange (StackOverflow family of sites) application for Windows Phone 7 that brings the popular family of sites to the mobile. In particular I was trying to indicate which answer in particular was the correct one. To do this I used the Image control (as above) to display a green tick icon, similar to that on the StackOverflow website and bind the Accepted property to controls it's visibility.

The Solution

Unfortunately the visibility property is of type System.Windows.Visibility. Therefore we need to implement IValueConverter to take our boolean property and convert that to System.Windows.Visibility. You can then add this IValueConverter implementation to your XAML as a resource and specify the converter as a part of the binding process in your XAML.

 

   1:      public class VisibilityConverter : IValueConverter
   2:      {
   3:          public object Convert(
   4:              object value,
   5:              Type targetType,
   6:              object parameter,
   7:              CultureInfo culture)
   8:          {
   9:              bool visibility = (bool)value;
  10:              return visibility ? Visibility.Visible : Visibility.Collapsed;
  11:          }
  12:   
  13:          public object ConvertBack(
  14:              object value,
  15:              Type targetType,
  16:              object parameter,
  17:              CultureInfo culture)
  18:          {
  19:              Visibility visibility = (Visibility)value;
  20:              return (visibility == Visibility.Visible);
  21:          }
  22:      }

 

And the XAML:

 

   1:  <helpers:VisibilityConverter x:Key="VisibilityConverter"></helpers:VisibilityConverter>

   1:  <Image Source="/Images/Icons/correct_answer.png" Visibility="{Binding Accepted, Converter={StaticResource VisibilityConverter}}"></Image>

 

Again it may seem a little obvious but I hope this comes in handy for those new to Silverlight databinding.

blog comments powered by Disqus