Silverlight - Converters Example



In this article I am introducing how converters work in Silverlight. This is part of a series intended for Silverlight Beginners.

Table creation :

create table tb_status
(
status_id int identity primary key,
status_name varchar(25
)
)

Record Insertion :

insert into tb_status values('Online');
insert into tb_status values('Offline');
insert into tb_status values('Busy');

Creating a Data Model :

Silverlight - Converters Example

Create a Silverlight enabled WCF Service :

Silverlight - Converters Example

public class DataService
{
    [OperationContract]
    public IEnumerable<StatusTable> GetStatus()
    {
        ProjectsDataEntities context = new ProjectsDataEntities();
        var status = from o in context.tb_status
                     select new StatusTable
                     {               
                        statusid = o.status_id,
                        statusname = o.status_name
                     };
        return status;
    }
   
}


In the method that I have added I just get the status from the table. I use a POCO StatusTable to get the table values then I wrap those values in a POCO and send it across to the Client.

My POCO looks like :

public class StatusTable
{
      public int statusid { get; set ;}
      public string statusname { get ; set ;}
}


Now lets get into the subject of this article. My intent is to display a ListBox which gets the status from the database and displays it. But wait a minute; I don't want to display my status to the user as Online, Offline, Busy. That is not what I want. It would not make my UI presentable to the Client. My Client actually wants me to display the status in colors say Offline would be Grey, Online would be Green and Busy would be Yellow.

Now how am I going to do that? Well Silverlight does provide us with Converters which would convert the a value to another value in order to make it presentable using the XAML.


Let us now start doing it.

I use a IvalueConverter in my example. Check this out for references

http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter%28v=vs.95%29.aspx

I create a class called BoolToBrushConverter. I implement the interface IvalueConverter.

namespace System.Windows.Data
{
    // Summary:
    //     Exposes methods that allow modifying the data as it passes through the binding
    //     engine.
    public interface IValueConverter
    {
        // Summary:
        //     Modifies the source data before passing it to the target for display in the
        //     UI.
        //
        // Parameters:
        //   value:
        //     The source data being passed to the target.
        //
        //   targetType:
        //     The System.Type of data expected by the target dependency property.
        //
        //   parameter:
        //     An optional parameter to be used in the converter logic.
        //
        //   culture:
        //     The culture of the conversion.
        //
        // Returns:
        //     The value to be passed to the target dependency property.
        object Convert(object value, Type targetType, object parameter, CultureInfo culture);
        //
        // Summary:
        //     Modifies the target data before passing it to the source object. This method
        //     is called only in System.Windows.Data.BindingMode.TwoWay bindings.
        //
        // Parameters:
        //   value:
        //     The target data being passed to the source.
        //
        //   targetType:
        //     The System.Type of data expected by the source object.
        //
        //   parameter:
        //     An optional parameter to be used in the converter logic.
        //
        //   culture:
        //     The culture of the conversion.
        //
        // Returns:
        //     The value to be passed to the source object.
        object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture);
    }
}


Let me implement the interface now. In the Convert method I check for the value and based on the integer value I convert it into a respective Color.

public class BoolToBrushConverter : IValueConverter
{
    public object Convert(
        object value,
        Type targetType,
        object parameter,
        CultureInfo culture)
    {
        Brush b = null;

        // Only apply the conversion if value is assigned and
        // is of type bool.
        if (value != null &&
            value.GetType() == typeof(Int32))
        {
            // true is painted with a green brush,
           
// false with a red brush.

            if (System.Convert.ToInt32(value) == 1)
            {
                b = new SolidColorBrush(Colors.Green);
            }
            if (System.Convert.ToInt32(value) == 2)
            {
                b = new SolidColorBrush(Colors.Red);
            }
            if (System.Convert.ToInt32(value) == 3)
            {
                b = new SolidColorBrush(Colors.Orange);
            }
            if (System.Convert.ToInt32(value) == 4)
            {
                b = new SolidColorBrush(Colors.Purple);
            }
        }

        return b;
    }

    // Not used.
    public object ConvertBack(
        object value,
       Type targetType,
        object parameter,
        CultureInfo culture)
    {
        return null;
    }
} 

In this example I am not putting anything into the database so I do not need to implement the ConvertBack() method.


Now let's get to the XAML.

Add this as reference:

xmlns:local="clr-namespace:SLConverter"


Add the Converter as a User Control Resource:

<UserControl.Resources>
        <local:BoolToBrushConverter x:Key="boolToBrushConverter" />
 </UserControl.Resources>

Now the Main Part looks like below :

    <Grid x:Name="LayoutRoot" Background="White">
        <ListBox HorizontalAlignment="Left" Name="CustomerGrid1" VerticalAlignment="Top"  ScrollViewer.HorizontalScrollBarVisibility="Hidden" ScrollViewer.VerticalScrollBarVisibility="Hidden" Margin="23,-6,0,0" Background="Transparent" >
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal" />
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>

            <ListBox.ItemTemplate >
                <DataTemplate >
                    <StackPanel Orientation="Horizontal" >
                                <Rectangle Fill="{Binding Path=statusid,
          Converter={StaticResource
boolToBrushConverter}}"
         Height="12" Width="12" RadiusY="2" RadiusX
="2"/>
                    </StackPanel>
                </DataTemplate>

            </ListBox.ItemTemplate>

        </ListBox>
    </Grid>


In the above code the following line is the key for checking out how the binding is done. I fill the rectangle using the Color which I get after binding the status Id and converting using BooltoBrushConverter.

<Rectangle Fill="{Binding Path=statusid,Converter={StaticResource boolToBrushConverter}}"

Let's complete the Binding process by binding in the Code Behind:

public partial class MainPage : UserControl

{
    public MainPage()
    {
        InitializeComponent();
        DataServiceClient client = new DataServiceClient();

        client.GetStatusCompleted += new EventHandler<GetStatusCompletedEventArgs>(client_GetStatusCompleted);
        client.GetStatusAsync();
    }

    void client_GetStatusCompleted(object sender, GetStatusCompletedEventArgs e)
    {
        CustomerGrid1.ItemsSource = e.Result;
    }
}


Let's give it a run:

Silverlight - Converters Example

Great Works ! Happy Coding !

Up Next
    Ebook Download
    View all
    Learn
    View all