I was working on a Silverlight 4 project with a coworker a few days ago and needed to display a list of objects with different editors based on the type of object. The first thing that came to my mind was to use a DataTemplateSelector. I found out quickly that the Silverlight team – for whatever reason – decided they didn’t want to include a DataTemplateSelector. Frustrated, we turned to Google and found a blog post by Mike Gold that was basically exactly what we needed.  I made a few modifications to how he implemented this solution (which I think make it simpler), so I’m posting it here in case it might help someone else.

The idea is to use a custom IValueConverter to convert data templates into content inside of a ContentControl’s Content property. Here is the code for the converter that I used in my sample:
public class CustomerDataTemplateSelectorConverter : IValueConverter
{
    public DataTemplate ActiveCustomerDataTemplate { get; set; }
    public DataTemplate InactiveCustomerDataTemplate { get; set; }

    public object Convert(object value, Type targetType,
                            object parameter, CultureInfo culture)
    {
        var customer = value as Customer;
        if (customer != null)
        {
            return customer.IsActive
                        ? ActiveCustomerDataTemplate.LoadContent()
                        : InactiveCustomerDataTemplate.LoadContent();
        }
        return null;
    }

    public object ConvertBack(object value, Type targetType,
                                object parameter, CultureInfo culture)
    {
        // this method should never be called
        throw new NotImplementedException();
    }
}
 

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Looking for something?

Use the form below to search the site:


Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...

Archives

All entries, chronologically...