一个列表框的两个itemtemplates

xSe*_*der 37 wpf listbox itemtemplate

我上了课FruitViewModel.它描述了ListBox项目的ViewModels .

<ListBox ItemsSource="{Binding Fruits}">
Run Code Online (Sandbox Code Playgroud)

而且我有

class BananaViewModel : FruitViewModel
Run Code Online (Sandbox Code Playgroud)

class AppleViewModel : FruitViewModel
Run Code Online (Sandbox Code Playgroud)

Fruits包含绑定的BananaViewModels和AppleViewModels ItemsSource.

如何为苹果和香蕉制作不同的模板?它们应该在一个列表中,但具有不同的模板

Joh*_*wen 71

您可以通过指定DataType不带a来定义适用于特定类型的任何实例的DataTemplates x:Key.使用此方法您不会分配任何内容ItemTemplate- 模板会自动应用.

<ListBox ItemsSource="{Binding Path=MixedList}">
    <ListBox.Resources>
        <DataTemplate DataType="{x:Type local:BananaViewModel}">
            <TextBlock Text="{Binding Name}" Foreground="Yellow"/>
        </DataTemplate>
        <DataTemplate DataType="{x:Type local:AppleViewModel}">
            <TextBlock Text="{Binding Name}" Foreground="Red"/>
        </DataTemplate>
    </ListBox.Resources>
</ListBox>
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你提到你必须省略x:Key! (2认同)
  • 如果您想在 &lt;Window.Resources&gt; 中拥有 2 个 DataTemplates。如何将 'ItemTemplate=' 属性设置为多个 DataTemplate?特别是我想将 TreeView 的 2 个 HierarchicalDataTemplates 外包给 &lt;Window.Resources&gt;。多重绑定可能是一个解决方案。 (2认同)