DataTempleSelector 不调用 SelectTemplate

DataTempleSelector Not Calling SelectTemplate

我一直在尝试为我的 WPF 列表框获取一个简单的 DataTempleSelector,但一直没有成功。我在 SelectTemplate 上设置了一个断点,但它从未被调用过。知道我在这里做错了什么吗?

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>

您已将 ListBox 控件中项目的 UI 硬编码为 ListBoxItems

如果您想使用 ItemTemplate,则必须使用 ListBoxItemsSource 属性,然后您的 DataTemplate 将应用于每个项目.

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