Click here to Skip to main content
15,867,568 members
Articles / Silverlight
Tip/Trick

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 43.4K   3   5
Silverlight with IValueConverter to to Format Data

Introduction


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.

Background


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


C#
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(
                    200,
                    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"
            xmlns:converters="MyApp.Library.Converters"
            mc:Ignorable="d">

Create key in resource/style for use in page.
Collapse

<UserControl.Resources>
        <converters:NumericToColorConverter x:Key="NumericToColorConverter" />
    </UserControl.Resources>

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

<ItemsControl x:Name="myControl"
        VerticalAlignment="Top"
        ItemsSource="{Binding Employees}">
                <ItemsControl.ItemTemplate>
                             <DataTemplate>
                             <Border BorderThickness="1"
                             CornerRadius="5"
                             VerticalAlignment="Top"
                             BorderBrush="Black"
                             Width="150"
                             Height="50"
                             Margin="0"
                             Background="{Binding EmployeeID, 
                             Converter={StaticResource NumericToColorConverter}}">
                  <TextBlock Text="{Binding EmployeeName}"
                             FontWeight="Bold"
                             Height="25" />
                   </Border>
                </DataTemplate>
         </ItemsControl.ItemTemplate>
   </ItemsControl>

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.

C#
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;
                }
                else
                {
                    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


<UserControl.Resources>
        <converters:VisibilityConverter x:Key="VisibilityConverter" />
    </UserControl.Resources>

In XAML Binding


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

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"
                    HorizontalAlignment="Center"
                    VerticalAlignment="Center"
                    Source="/MyApp;component/Resources/Default/Images/abc.jpg" />
         </Border>

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

Summary


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.

License

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.

http://hirenkhirsaria.blogspot.com/

Comments and Discussions

 
QuestionIsImageVisible Pin
Ahnad Basher Auod6-Mar-16 13:43
Ahnad Basher Auod6-Mar-16 13:43 
AnswerRe: IsImageVisible Pin
Hiren Khirsaria6-Mar-16 18:03
professionalHiren Khirsaria6-Mar-16 18:03 
GeneralRe: IsImageVisible Pin
Ahnad Basher Auod7-Mar-16 0:28
Ahnad Basher Auod7-Mar-16 0:28 
Thank you
GeneralReason for my vote of 5 It's really good for silverlight beg... Pin
gowthamg27-Nov-11 21:09
gowthamg27-Nov-11 21:09 
GeneralReason for my vote of 2 ok Pin
Stole98-Aug-11 20:56
Stole98-Aug-11 20: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.