Furnes
Furnes

Reputation: 382

Different views for each item in listview

I did a couple of smart things just before the summer vacation and for some reason I deleted the code and can't remember how I solved one Issue, so I turn to the experts of StackOverflow.

The basic idea is this. I have a listview bound to an observable collection of viewmodels. The items in the list are of type Generic, or an inherited class that we can call specialized. Now if the item is of type Generic, I want the generic view to be displayed in the list, and if the type is Specialized I want Specialized view to be displayed. I've set up a datatemplate for each viewmodel, binding it to its view. But for some reason, instead of loading the view, the only thing displayed is the full classname of the viewmodel. I know I'm missing something stupid, but apparently I left my brain at the beach.

Here is the xaml (namespace etc removed):

<UserControl x:Class="ReportHostView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:vmrep="ViewModel.Report"            
         xmlns:vwrep="View.Report" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
    <DataTemplate x:Key="DefaultDataTemplate" DataType="{x:Type vmrep:GenericItemViewModel}">
        <vwrep:GenericItemView />
    </DataTemplate>

    <DataTemplate x:Key="SpecializedDataTemplate" DataType="{x:Type vmrep:SpecializedItemViewModel}">
        <vwrep:SpecializedItemView />
    </DataTemplate>

    <DataTemplate x:Key="ItemTemplate">
        <ContentPresenter Content="{Binding}" />
    </DataTemplate>
</UserControl.Resources>
<Grid Width="1024" Height="800">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="200" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <ListView ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}" ItemTemplate="{StaticResource ItemTemplate}">
    </ListView>
</Grid>

Upvotes: 0

Views: 1478

Answers (1)

takemyoxygen
takemyoxygen

Reputation: 4394

Try to do the following: modify DataTemplates to be default ones by removing x:Key attributes:

<DataTemplate DataType="{x:Type vmrep:GenericItemViewModel}">
    <vwrep:GenericItemView />
</DataTemplate>

<DataTemplate DataType="{x:Type vmrep:SpecializedItemViewModel}">
    <vwrep:SpecializedItemView />
</DataTemplate>

and then do not explicitly set Item template to your ListView

<ListView ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}">

Upvotes: 1

Related Questions