Jon Dosmann
Jon Dosmann

Reputation: 737

DataTempleSelector Not Calling SelectTemplate

I've been trying to get a simple DataTempleSelector going for my WPF Listbox and I've not had any luck. I have a break point set at the SelectTemplate and it's just never getting called. Any idea what I'm doing wrong here?

C#:

public class ListBoxTemplateSelector : DataTemplateSelector
{
    public DataTemplate DefaultnDataTemplate { get; set; }
    public DataTemplate OverrideDataTemplate { get; set; }

    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        string listboxItem = item as string;
        if (listboxItem == "Apples" || listboxItem == "Oranges")
        {
            return OverrideDataTemplate;
        }

        return DefaultnDataTemplate;
    }
}

XAML:

<Window.Resources>
    <DataTemplate x:Key="DefaultDataTemplate">
        <Grid Margin="4" MinHeight="25" Background="Blue"/>
    </DataTemplate>

    <DataTemplate x:Key="OverrideDataTemplate">
        <Grid Margin="4" MinHeight="25" Background="Black"/>
    </DataTemplate>

    <converters:ListBoxTemplateSelector 
        x:Key="templateSelector"
        DefaultnDataTemplate="{StaticResource DefaultDataTemplate}"
        OverrideDataTemplate="{StaticResource OverrideDataTemplate}"/>

</Window.Resources>

<Grid>
    <ListBox ItemTemplateSelector="{StaticResource templateSelector}">
        <ListBox.Items>
            <ListBoxItem Content="Apple"/>
            <ListBoxItem Content="Banannas"/>
            <ListBoxItem Content="Oranges"/>
            <ListBoxItem Content="Lemons"/>
        </ListBox.Items>
    </ListBox>
</Grid>

Upvotes: 2

Views: 513

Answers (1)

Glen Thomas
Glen Thomas

Reputation: 10744

You have hard-coded the UI of the items in the ListBox control as ListBoxItems

If you want to make use of the ItemTemplate you will have to use the ItemsSource property of the ListBox then your DataTemplate will be applied to each item.

i.e.

<ListBox ItemTemplateSelector="{StaticResource templateSelector}" ItemsSource="{Binding Fruits}">
</ListBox>

Upvotes: 1

Related Questions