In my Silverlight project, I needed to use DataTemplateSelector. I found a way to implement this (as it's not present in the framework) here : http://www.codeproject.com/KB/silverlight/SLTemplateSelector.aspx

This method has been working correctly in other places of my code, but this time it doesn't work. The problem is that the TemplateSelector is never called (I even tried to put a breakpoint in the constructor, but it was never hit). Can you see a problem in my code ? I used a debug converter, and could see that my ListBox's ItemsSource is correctly set.

Thanks in advance !

XAML:

<ListBox Name="DestinationsList" Grid.Column="2" ItemsSource="{Binding}">
<ListBox.ItemTemplate>      
    <DataTemplate>
        <helper:TargetTemplateSelector Content="{Binding}">
            <helper:TargetTemplateSelector.FirstTemplate>
                <DataTemplate>
                    <TextBlock Text="Test1" />
                </DataTemplate>
            </helper:TargetTemplateSelector.FirstTemplate>
            <helper:TargetTemplateSelector.SecondTemplate>
                <DataTemplate>
                    <TextBlock Text="Test2" />
                </DataTemplate>
            </helper:TargetTemplateSelector.SecondTemplate>
        </helper:TargetTemplateSelector>
    </DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

TemplateSelector class:

public class TargetTemplateSelector : DataTemplateSelector
{
    public DataTemplate FirstTemplate { get; set; }
    public DataTemplate SecondTemplate { get; set; }        

    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        MyClass1 target = item as MyClass1;

        if (target != null)
        {
            if (target.Profile is MyClass2)
            {
                return this.FirstTemplate;
            }
            else if (target.Profile is MyClass3)
            {
                return this.SecondTemplate;
            }
            else
            {
                throw new NotImplementedException();
            }
        }

        return base.SelectTemplate(item, container);
    }
}
有帮助吗?

解决方案

So dumb... I'll take the excuse it's friday...

The problem was that the value bound to the listbox wasn't a collection...

You may start throwing stones...

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top