Click here to Skip to main content
15,498,859 members
Articles / Silverlight
Posted 2 Aug 2011

Tagged as


3 bookmarked

Data Binding Using IValueConverter in Silverlight

Rate me:
Please Sign up or sign in to vote.
4.70/5 (4 votes)
2 Aug 2011CPOL2 min read
Silverlight with IValueConverter to to Format Data


Silverlight is used for creating rich RIA application. if we wish to bind value in XAML, we are using dependencyproperty and dependencyobject.

One more features of Silverlight for data biniding process is IValueConverter.

IValueConverter is used for formatting and binding data to silverlight XAML control.


When we are binding data to controls there will be times when the data needs to be modified.

a value converter is used in that case and you can re-use your source.

In this article we go through creating converter and code for some value converter examples.

Using the Code

Using Value Converter you can convert:

  • Boolean value to Visibility of control
  • Double value to Percentage
  • Double to Opacity of Control
  • Numeric to Color of Control

Example 1: Numeric to Color of Control

In my XAML page, i am binding Employee List to itemssource and i want to give background color of each employee different display.

First I am creating one converter to convert numeric value to color brush.

Class : NumericToColorConverter.cs

public class NumericToColorConverter : IValueConverter
        public object Convert(object value, Type targetType, 
            object parameter, System.Globalization.CultureInfo culture)
            Int32 id = System.Convert.ToInt32(value);

            LinearGradientBrush brush = new LinearGradientBrush();
            brush.StartPoint = new Point(0, 1);
            brush.EndPoint = new Point(0, 0);
            brush.GradientStops.Add(new GradientStop() { Color = Colors.White, 
                Offset = 0 });
            brush.GradientStops.Add(new GradientStop()
                Color = Color.FromArgb(
                    System.Convert.ToByte((id * 103) % 256),
                    System.Convert.ToByte((id * 157) % 256),
                    System.Convert.ToByte((id * 233) % 256)
                Offset = 1

            return brush;

        public object ConvertBack(object value, Type targetType, object parameter, 
            System.Globalization.CultureInfo culture)
            throw new NotImplementedException();

IValueConverter has two methods Convert and ConvertBack to convert passed value.

In Convert method:

  • first field has value which we passsed from data binding in XAML page.
  • second field is parameter passed as ConverterParameter at the time of binding.
  • third field is used when we are working on globalization.

You can convert Numeric values to SolidColorBrush or LinearGradientBrush.

Converting numeric value to color you have to convert value to bytes in (A,R,G,B) format that is Red,Green and Blue value and A parameter is for Opacity.

My XAML Page

first you need to add reference of converter in usercontrol.

<UserControl x:Class="MyApp:MyTestPage"

Create key in resource/style for use in page.

        <converters:NumericToColorConverter x:Key="NumericToColorConverter" />

Bind Data in Control and pass Converter to convert and get back Background Color.

<ItemsControl x:Name="myControl"
        ItemsSource="{Binding Employees}">
                             <Border BorderThickness="1"
                             Background="{Binding EmployeeID, 
                             Converter={StaticResource NumericToColorConverter}}">
                  <TextBlock Text="{Binding EmployeeName}"
                             Height="25" />

So, this way you can convert value to your formatted value.

Example 2 : Boolean to Visibility Converter

In this example you are going to read about, you have boolean value (true/false) based on that you return Visibility of control (visible/collapsed) from converter.

public class VisibilityConverter : IValueConverter
        public object Convert(object value, Type targetType, object parameter, 
            System.Globalization.CultureInfo culture)
            Boolean result = true;

            if (parameter != null) Boolean.TryParse(parameter.ToString(), out result);

            if (value != null && value is Boolean)
                if (System.Convert.ToBoolean(value) == result)
                    return System.Windows.Visibility.Visible;
                    return System.Windows.Visibility.Collapsed;

            return value;

        public object ConvertBack(object value, Type targetType, object parameter, 
            System.Globalization.CultureInfo culture)
            throw new NotImplementedException();

In above code if you are passing true value at binding source and pass to converter, it will return Visibility.Visible and it value is false it will return Visibility.Collapsed.

You can also pass converter parameter to get result based on passed parameter.

Creating resource

        <converters:VisibilityConverter x:Key="VisibilityConverter" />

In XAML Binding

I am binding IsImageVisible property to True.
<Border Background="White"
                 Visibility="{Binding Path=IsImageVisible,
                 Converter={StaticResource VisibilityConverter}}">
             <Image Stretch="Uniform"
                    Source="/MyApp;component/Resources/Default/Images/abc.jpg" />

So, it will return Visibility to Visible.

Now, Using Converter Parameter

In XAML Binding

I am binding IsImageVisible property to True and ConverterParemeter to False.

<Border Background="White"
                 Visibility="{Binding Path=IsImageVisible,
          Converter={StaticResource  VisibilityConverter},ConverterParameter=False}">
             <Image Stretch="Uniform"
                    Source="/MyApp;component/Resources/Default/Images/abc.jpg" />

Using above code you will get Visibility to Collapsed. You can use mulitple functionality by passing converterparameter to converter.


In this article you learned how to use a Value Converter class to take data that is in one format and convert it to another format prior to displaying that value in a XAML control.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Team Leader Reputed IT Company
India India
Having 9+ years of experience in Microsoft.Net Technology.
Experience in developing applications on Microsoft .NET Platform ( Asp.Net, WPF, Silverlight, Windows Phone 7/8).
Experience and knowledge of software design methodologies (Agile), object oriented design, and software design patterns (MVVM).
Experience in Developing android mobile application using Xamarin (mono for android) framework.

Comments and Discussions

QuestionIsImageVisible Pin
Ahnad Basher Auod6-Mar-16 14:43
MemberAhnad Basher Auod6-Mar-16 14:43 
AnswerRe: IsImageVisible Pin
Hiren Khirsaria6-Mar-16 19:03
professionalHiren Khirsaria6-Mar-16 19:03 
GeneralRe: IsImageVisible Pin
Ahnad Basher Auod7-Mar-16 1:28
MemberAhnad Basher Auod7-Mar-16 1:28 
GeneralReason for my vote of 5 It's really good for silverlight beg... Pin
gowthamg27-Nov-11 22:09
Membergowthamg27-Nov-11 22:09 
GeneralReason for my vote of 2 ok Pin
Stole98-Aug-11 21:56
MemberStole98-Aug-11 21:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.