【问题标题】:Different views for each item in listview列表视图中每个项目的不同视图
【发布时间】:2012-08-10 06:50:58
【问题描述】:

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

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

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

【问题讨论】:

    标签: wpf mvvm


    【解决方案1】:

    尝试执行以下操作:通过删除 x:Key 属性将 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}">
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多