.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> Silverlight >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Silverlight - Converters Example

Posted By:Mahadesh Mahalingappa       Posted Date: August 06, 2011    Points: 200    Category: Silverlight    URL: http://www.dotnetspark.com  

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

Silverlight -  Converters Example:

In this article I am giving a introduction of 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 :





Create a Silverlight enabled WCF Service :





public class DataService
    {
        [OperationContract]
        public IEnumerable 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 aim 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 achieve this .  Well Silverlight does provide us with Converters which would convert the a value to another value inorder 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(v=vs.95).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 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 to the database so I do not need to implement the ConvertBack() method .


Now lets get to the Xaml :

Add this as reference  xmlns:local="clr-namespace:SLConverter"


Add the Converter as a User Control Resource


  
 


Now the Main Part looks like below :

    
        
            
                
                    
                
            

            
                
                    
                                
                    
                


            

        
    



In the above code the below line is the key check 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}}"


Lets complete the Binding process my binding in the Code Behind :

public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            DataServiceClient client = new DataServiceClient();

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

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


Let's give it a run :




Great Works !  Happy Coding !


 Subscribe to Articles

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend