.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 >> WPF >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Value Converter In WPF - Part I

Posted By:Diptimaya Patra       Posted Date: May 30, 2010    Points: 25    Category: WPF    URL: http://www.dotnetspark.com  

Value Converter In WPF - Part I. In this article series we will see what are Value Converters and how it can be used and usefulness in WPF.
 

Value Converters

The first thing we should ask is; what is Value Converter(s)?

Well, to say it in simple words it is a Converter that converts value based on input as Source and provides output as Target.

Hope the following figure make things easier to understand:

image1.gif

As you can see from the above image we have both way arrows in between Source and Target. That means: the value converter not only designed to take input from the target and modify the source, it also works when source data is updated on target. As you are familiar with two way bindings in WPF.

We will straight away create a WPF Application and create simple converters to understand it.

Creating WPF Application

Fire up Visual Studio 2008 and Create a WPF Application, name it as ConvertersInWPF.

image2.gif

Now let's think what simple converter we can use!

Let's say we will create one or more Converters. So we will keep inside a folder:

image3.gif

Now add a class to the Converter Folder, name it as StatusToColor.cs

image4.gif

Here's the idea, we will have a list of Requests and we will display the status of the request in colors.

Let's have the following entity class that represent Request structure.

image4_5.gif

Code view of the above image
public class Request
{
    #region Enum-Status
    public enum Status
    {
        Submitted,
        Assigned,
        InProgress,
        Resolved,
        Closed
    }
    #endregion

    #region Public-Properties
    public string Title { get; set; }
    public Status RequestStatus { get; set; }
    #endregion
}

As you see in above code display we have an Enum as Status and we have 5 values inside of it; such as: Submitted, Assigned, InProgress, Resolved, and Closed.

Now based on above information we will modify our StatusToColor.cs

Implement IValueConverter in the above class.

As the namespace is not referred, we have to type it upto end and after resolving you would see the following namespace to be used.

image5.gif

Now we have to implement the methods in this Interface. So resolve the interface again.

image6.gif

Select the Implement interface option: the following methods would be defined as follows:

image7.gif

As we discussed in the beginning that the Source and Target can convert each other so that's why we have two methods defined. Convert would do conversion from Source -> Target and ConvertBack would do conversion from Target -> Source.

For the time being we will proceed with Convert method.

First we will define the Enum here again.

image8.gif

Code view of the above image
public enum Status
{
    Submitted,
    Assigned,
    InProgress,
    Resolved,
    Closed
}

We can use the same name but for understanding I am giving a different name.

Remove the throw new Exception(); and replace with following code.

image9.gif

Code view of the above image

public object Convert(object value, Type targetType,
    object parameter, System.Globalization.CultureInfo culture)
{
    Request.Status state = (Request.Status)value;
    Status stateColor = (Status)Enum.Parse(typeof(Status), value.ToString());

    switch (state)
    {
        case Request.Status.Submitted:
            if (stateColor == Status.Submitted)
            { return new SolidColorBrush(Colors.Red); }
            break;
        case Request.Status.Assigned:
            if (stateColor == Status.Assigned)
            { return new SolidColorBrush(Colors.Orange); }
            break;
        case Request.Status.InProgress:
            if (stateColor == Status.InProgress)
            { return new SolidColorBrush(Colors.Gold); }
            break;
        case Request.Status.Resolved:
            if (stateColor == Status.Resolved)
            { return new SolidColorBrush(Colors.YellowGreen); }
            break;
        case Request.Status.Closed:
            if (stateColor == Status.Closed)
            { return new SolidColorBrush(Colors.Gray); }
            break;
    }
    return new SolidColorBrush(Colors.Transparent);
}

The above code display for converting and returning is a very simple logic to convert.

Now for user's knowledge about the colr use we would put the colors with some information.

image10.gif

Now we have bind the converter in the XAML, for that first thing we have to do is to use the namespace.

xmlns:converter="clr-namespace:ConvertersInWPF.Converters"

Now we have customized the DataGrid, to have a TextBoxColumn and a TemplateColumn to display the Status as defined Color.

image12.gif

Code view of the above image

  
    
    
      
        
          
            
          
        
      
    
  

Now for the Rectangle in TemplateColumn we will fill using the Converter:

Fill="{Binding RequestStatus, Converter={StaticResource statusToColor}}

We are good to go, and run the application. But before that let's have some sample data to display.

image14.gif

Code view of the above image
public Window1()
{
    InitializeComponent();
    ObservableCollection requestList = new ObservableCollection 
    {
        new Request{Title="Add Employee To Active Directory", 
            RequestStatus=Request.Status.Closed},
        new Request{Title="Create Requested AD Distribution List", 
            RequestStatus=Request.Status.InProgress},
        new Request{Title="Install Windows Server 2008", 
            RequestStatus=Request.Status.Resolved},
        new Request{Title="Format System", 
            RequestStatus=Request.Status.Assigned},
        new Request{Title="Change Passowrd", 
            RequestStatus=Request.Status.Assigned},
        new Request{Title="Install Office 2007", 
            RequestStatus=Request.Status.Resolved},
        new Request{Title="Grant Access of Facebook", 
            RequestStatus=Request.Status.InProgress},
        new Request{Title="Grant Access of Youtube", 
            RequestStatus=Request.Status.Submitted},
        new Request{Title="Install Visual Studio 2010 RC", 
            RequestStatus=Request.Status.Submitted},
        new Request{Title="Install Expression Blend 4 Beta", 
            RequestStatus=Request.Status.InProgress},
    };
    dgRequests.ItemsSource = requestList;
}


You would see the colors are reflected as per the data given.

image15.gif

You can also download the sample project used in above example

Hope this article helps.


 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