列表视图中每个项目的不同视图

时间:2012-08-10 06:50:59

标签: wpf mvvm

我在暑假前做了一些聪明的事情,由于某种原因,我删除了代码,不记得我是如何解决一个问题的,所以我转向StackOverflow的专家。

基本理念是这样的。我有一个listview绑定到一个可观察的视图模型集合。列表中的项目是Generic类型,或者我们可以调用专用的继承类。现在,如果项目是Generic类型,我希望通用视图显示在列表中,如果类型是Specialized,我想要显示Specialized视图。我为每个viewmodel设置了一个datatemplate,并将其绑定到它的视图。但出于某种原因,显示的唯一内容是视图模型的完整类名,而不是加载视图。我知道我错过了一些愚蠢的东西,但显然我把我的大脑留在了海滩上。

这是xaml(名称空间等已删除):

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

1 个答案:

答案 0 :(得分:1)

尝试执行以下操作:通过删除x:Key attributes:

将DataTemplates修改为默认值
<DataTemplate DataType="{x:Type vmrep:GenericItemViewModel}">
    <vwrep:GenericItemView />
</DataTemplate>

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

然后不要将Item模板显式设置为ListView

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