Getting by without a DataTemplateSelector in Silverlight
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();
}
}
I’ve put the sample code up on BitBucket: https://bitbucket.org/schmeling88/datatemplateselector-workaround/src
-
Meta



