views:

38

answers:

1

Hi! I want to set an ItemTimplate according to some property. I've just create a markup, where I set ItemTemplate like this:

<controls:Panorama Title="Some Title" ItemsSource="{Binding Modules}" ItemTemplate="{Binding Id, Converter={StaticResource ControlTemplateConverter}}">

    <controls:Panorama.Background>
        <ImageBrush ImageSource="PanoramaBackground.png"/>
    </controls:Panorama.Background>

</controls:Panorama>

And implement ControlTemplateConverter like this:

public class ControlTemplateConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        StringBuilder sbTemp = new StringBuilder();
        sbTemp.Append("<DataTemplate ");
        sbTemp.Appen("xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' ");
        sbTemp.Append("xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' ");
        sbTemp.Append("<StackPanel>");
        sbTemp.Append("<TextBlock Text=\"News News\" />");
        sbTemp.Append("</StackPanel>");
        sbTemp.Append("</DataTemplate>");
        return (DataTemplate)XamlReader.Load(sbTemp.ToString());
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

I registered a converter:

<UserControl.Resources>
    <converter:ControlTemplateConverter x:Key="ControlTemplateConverter" />
</UserControl.Resources>

But when I set a breakpoint in ControlTemplateConverter.Convert it never stops in debug. ItemSource loads everytime. What's wrong? Thank you.

A: 

I suspect that the binding fails to find the property Id in the same DataContext that the Modules property is found. Hence there is no call to the converter. This is probably because Id is actually a property of each Module and somehow you imagine that the ItemTemplate binding gets resolved for each item. It doesn't. You have one template that gets applied to all items in the ItemsSource.

AnthonyWJones
When I remove Id from Binding in Converter I receive the parent of Modules. How can I get a context of binding object or how can I bind a template according to the property of some object in other way?
SuperXMan