Skip navigation links
Community
Events
Thought Leadership
Community Site
AIC CAM
Blogs

Silverlight Value Converters 

Tags: Silverlight, Microsoft, Application Development and Integration

Value converters are a simple object implementing the IValueConverter interface that are used to take in a value and based on that value, derive another value.  Typically, value converters are used for display logic.  For example, we may create a value converter that will accept a Product as its input and produce a blue color brush if the product is not on sale, or a red one if it is.  Or if the product is out of stock, produce an “out of stock” image to be displayed.  Another common use for value converters is determining Visibility of an item based on some conditions of the item itself.

Value Converters in Silverlight (WPF) are a great way to encapsulate display logic to be reused across multiple pages or controls.  Using standard object oriented techniques, like Interfaces and Inheritance, value converters can be very powerful and very flexible.

In this blog, I will demonstrate the basics of what you need to set up a Value Converter. 

First, some set up.  I am using a very trimmed down ViewModel pattern with basic DTOs (Data Transfer Objects) as my demo architecture.  We will begin with a standard ListBox to display a list of products.  The following setup will be used to demonstrate the value converter examples, which follow.

Product DTO:

 public class Product
 {
     public string Name { get; set; }
     public decimal Price { get; set; }
     public bool OnSale { get; set; }
 }

 

Our product DTO includes the name of the product, the price for the product and a flag indicating whether the product is on sale or not.

Product ViewModel:

public class PageViewModel
{
    private ObservableCollection<Product> _productList = null;
    public ObservableCollection<Product> ProductList
    {
        get
        {
            return _productList;
        }
        set
        {
            _productList = value;
        }
    }
 
    public PageViewModel()
    {
        ProductList = new ObservableCollection<Product>();
 
        ProductList.Add(new Product()
        {
            Name = "Computer Desk",
            OnSale = true,
            Price = 79.99m
        });
        ProductList.Add(new Product()
        {
            Name = "Computer Chair",
            OnSale = true,
            Price = 39.99m
        });
        ProductList.Add(new Product()
        {
            Name = "File Cabinet",
            OnSale = false,
            Price = 29.99m
        });
    }
}

 

A ViewModel is a standard pattern used in Silverlight and WPF.  It provides a layer for databinding and UI specific logic.  I wont go into great detail on the ViewModel pattern here – a coupe of internet searches will provide plenty of opinions on the pattern.  Our view model exposes an ObservableCollection for our UI databinding as well as some test data.

Finally, our test page XAML:

<UserControl x:Class="ValueConverterDemo.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:vm="clr-namespace:ValueConverterDemo.ViewModel">
    <UserControl.Resources>
        <vm:PageViewModel x:Name="pageViewModel" x:Key="pageViewModel" />
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" Background="White" DataContext="{StaticResource pageViewModel}" HorizontalAlignment="Center" VerticalAlignment="Center">
        <Border CornerRadius="5" BorderThickness="2" BorderBrush="Black" Padding="2" Background="Azure">
            <ListBox ItemsSource="{Binding ProductList}" BorderThickness="0" Background="Transparent">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="{Binding Name}" Width="150"/>
                            <TextBlock Text="{Binding Price}" Width="50" 
                                       HorizontalAlignment="Right"/>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </Border>
    </Grid>
</UserControl>

Our page.xaml consists of a border around a list box which displays our ProductList items, Name and Price. A little formatting was added as well.  here is our output:

VCImage1 

Basic Value Converter

This value converter is the most basic of converters.  It will evaluate the Product and change the color of the price if the product is on sale.

    public class PriceConverter : IValueConverter
    {
        #region IValueConverter Members
 
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Product product = value as Product;
            Brush brush = new SolidColorBrush(Colors.Black);
 
            if (product != null && product.OnSale)
                brush = new SolidColorBrush(Colors.Red);
 
            return brush;
        }
 
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            // For this demo, we are not using the ConvertBack.
            return null;
        }
 
        #endregion

 

The Value Converter implements the IValueConverter interface, which has two methods – Convert and ConvertBack.  For purposes of this example, we will not be working with ConvertBack at all, the Convert method is where we will focus all of our attention.  In the basic value converter above, we cast our “value” to a Product and set a default brush color.  Then, if the product cast was successful and the product is on sale, we set the brush color to Red. 

In order to use this value converter in our XAML, we need to include the namespace:

xmlns:conv="clr-namespace:ValueConverterDemo.Converters"

Declare the value converter in the user control’s resources.

 <UserControl.Resources>
    <vm:PageViewModel x:Name="pageViewModel" x:Key="pageViewModel" />
    <conv:PriceConverter x:Name="priceConverter" x:Key="priceConverter" />
 </UserControl.Resources>

 

Next we are able to add our value converter to the price display:

 <TextBlock Text="{Binding Price}" Width="50" 
            HorizontalAlignment="Right"
            Foreground="{Binding Converter={StaticResource priceConverter}}"/>

 

We add the Converter resource into the Foreground binding.  When the text block is databound, the item (in our case, Product) will be passed to the converter to be evaluated.  Our converter will evaluate the product and if it is on sale, it will set the foreground to red.  Here is the output:

VCImage2

Thats it!  Once you are used to writing value converter and thinking about your data visualization using value converters you will find numerous opportunities to streamline and reuse your display logic.  Time permitting, i would like to build on this blog entry to show examples of using Interfaces, Inheritance and parameters within the value converter.

 
Posted by Lendl, Jay on 20-May-09
0 Comments  |  Link to this post  | Bookmark this post with:        
 

Comments

Name:
URL:
Email:
Comments:
 
RSS Feed Feed your read!
Archives
April 2009 (3)
May 2009 (2)
June 2009 (1)
August 2009 (1)
September 2009 (2)
November 2009 (1)
Tag Cloud