开发者

ContentTemplateSelector and Choose Template based upon the ListBoxItem Selected Item

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 overri开发者_如何学Cde method in which I don't know how to access the TemplateName Property from parameter(object).

Any code would be helpful?


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜