0

我有一个 MyTypeOneViewModel 类型的对象,它显示在 ListView 的第一列中,我有一个 MyTypeTwoViewModel 类型的对象,它显示在我的 ListView 的第二列中。这两种类型都有一个 MyNestedViewModel 类型的属性。现在我想根据该属性的实际类型为 ListView 中的每个单元格显示不同的 DataTemplate。例如,如果该属性实际上包含一个 MyDoubleNestedViewModel,我想在该单元格中显示一个文本框,如果该属性包含一个 MyBooleanNestedViewModel,我想在 ListView 的该特定单元格中显示一个 ComboBox。请注意,DataTemplate 在每一行和每一列中可能会有所不同。

我可以在没有 TemplateSelector 的情况下实现这一点吗?WPF 能够根据绑定的类型自动选择正确的 DataTemplate。但这在 ListView 的这种嵌套场景中是否也能以某种方式工作?

4

2 回答 2

1

考虑以下选项:

1. 直接绑定到子属性。

将该列绑定到子属性(类型为MyNestedViewModel)而不是父属性。然后 WPF 将根据嵌套视图模型的类型而不是父视图模型的类型来选择模板。

<GridViewColumn DisplayMemberBinding="{Binding TheChildViewModel}"/>

ContentControl2.在您的单元格模板中包含一个。

在您的网格列模板中,将 a 绑定ContentControl到子属性:

<GridViewColumn.CellTemplate>
    <DataTemplate>
        <StackPanel>
            <Label Content="{Binding SomePropertyOnParentViewModel}"/>
            <ContentControl Content="{Binding TheChildViewModel}"/>
        </StackPanel>
    </DataTemplate>
</GridViewColumn.CellTemplate>
于 2009-04-07T09:31:52.320 回答
0

WPF 可以完全满足您的需求。

引用具有您的数据类型的程序集,并为您需要显示的每种类型添加一个 DataTemplate 资源。

 xmlns:ui="clr-namespace:YourAssembly"
    <Window.Resources>

        <DataTemplate DataType="ui:MyDoubleNestedViewModel ">
              <Grid Margin="5,5,5,5" >

                   <TextBlock Text="{Binding Path=Value}"/>                                                     
        </Grid>

        </DataTemplate>

        <DataTemplate DataType="ui:MyBooleanNestedViewModel ">
              <Grid Margin="5,5,5,5" >

                   <ComboBox ItemsSource="{Binding Path=Items}"/>                                                       
        </Grid>

        </DataTemplate>
    </Window.Resources>

现在,此模板将与此窗口中绑定到您的视图模型对象的任何列表或内容控件一起使用。您不需要指定 ItemTemplate 设置。

于 2009-04-07T17:19:31.587 回答