Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

wpf - two itemtemplates for one listbox

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

question from:https://stackoverflow.com/questions/4001535/two-itemtemplates-for-one-listbox

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...