views:

149

answers:

1

Hi All, I have a XMLDataProvider Static Resource as for my Data listing some products. I have two Controls as Master Detail scenerio 1) ListBox which lists all the Product Titles and 2) COntentControl which displays the Product details.

Now its working fine at the moment but the ContentControl is using a hard-coded Template. What I want is to display products with different templates and ContentControl 's ContentTemplate should be picked up dynamically based upon the Product's field (TemplateName). How can I do that? I'm stuck in writing the SelectTemplate override method in which I don't know how to access the TemplateName Property from parameter(object).

Any code would be helpful?

A: 

Are you saying that you want to look up a DataTemplate resource where the name is given by an attribute of an XmlNode? To do that, you could cast item to an XmlElement to find the value you want, and then call TryFindResource to do the resource lookup:

public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
    var fe = container as FrameworkElement;
    var element = item as XmlElement;
    if (fe != null && element != null)
    {
        var templateName = element.GetAttribute("TemplateName");
        if (templateName != null)
        {
            return fe.TryFindResource(templateName) as DataTemplate;
        }
    }
    return null;
}

You could also do something similar entirely in XAML by defining a style for the ContentControl that uses DataTriggers to set the ContentTemplate:

<Style x:Key="DynamicTemplateStyle" TargetType="ContentControl">
    <Style.Triggers>
        <DataTrigger Binding="{Binding XPath=@TemplateName}" Value="FirstTemplate">
            <Setter Property="ContentTemplate" Value="{StaticResource FirstTemplate}"/>
        </DataTrigger>
        <DataTrigger Binding="{Binding XPath=@TemplateName}" Value="SecondTemplate">
            <Setter Property="ContentTemplate" Value="{StaticResource SecondTemplate}"/>
        </DataTrigger>
        <!-- etc. -->
    </Style.Triggers>
</Style>
Quartermeister