two itemtemplates for one listbox

被刻印的时光 ゝ 提交于 2019-11-28 16:27:23

问题


I've got a class FruitViewModel. It describes ViewModels for ListBox items.

<ListBox ItemsSource="{Binding Fruits}">

And I've got

class BananaViewModel : FruitViewModel

and

class AppleViewModel : FruitViewModel

Fruits contains BananaViewModels and AppleViewModels which is bound to ItemsSource.

How can I make different templates for apples and bananas? They should be in one list but have different templates


回答1:


You can define DataTemplates that apply to any instance of a specific type by specifying the DataType without an x:Key. Using this method you don't assign anything to ItemTemplate - the templates are applied automatically.

<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>



回答2:


On the ListView in XAML you can declare an ItemTemplateSelector. The value for this will come from a static resource or similar.

The implementation of your template selector should implement DataTemplateSelector and will basically contain the 'if' statement that chooses the correct DataTemplate based on the bound item's type. It will likely find the DataTemplate from the passed in container's resources (probably using the FindResource function).

Edit: Good link perhaps? http://www.switchonthecode.com/tutorials/wpf-tutorial-how-to-use-a-datatemplateselector Dead link.



来源:https://stackoverflow.com/questions/4001535/two-itemtemplates-for-one-listbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!