DataTempleSelector未调用SelectTemplate

时间:2015-08-04 14:05:20

标签: c# wpf datatemplate datatemplateselector

我一直试图为我的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>

1 个答案:

答案 0 :(得分:1)

您已将ListBox控件中的项目的用户界面硬编码为ListBoxItems

如果您想使用ItemTemplate,则必须使用ItemsSource的{​​{1}}属性,然后您的DataTemplate将应用于每个项目。

ListBox