DataTempleSelector没有调用SelectTemplate

本文关键字:SelectTemplate 调用 DataTempleSelector | 更新日期: 2023-09-27 18:06:22

我一直试图得到一个简单的DataTempleSelector去我的WPF列表框,我没有任何运气。我在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>

DataTempleSelector没有调用SelectTemplate

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

如果你想使用ItemTemplate,你必须使用ListBoxItemsSource属性,然后你的数据模板将应用于每个项目。

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