如何从WPF后面的代码中使用ItemsControl创建DataTemplate

问题描述 投票:1回答:2

我有一个带有一些恒定GridViewColumns的自定义ListView,我像这样在XAML中创建

<GridViewColumn Header="Name" Width="150">
    <GridViewColumn.CellTemplate>
        <DataTemplate>
            <ItemsControl ItemsSource="{Binding ListOfSubObjects}">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <StackPanel Orientation="Vertical"></StackPanel>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding SubObjectName}"/>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </DataTemplate>
    </GridViewColumn.CellTemplate>
</GridViewColumn>

ListView的ItemSource本身是对象列表,它们本身包含一个子对象列表(ListOfSubObjects),这些子对象具有我要绑定所显示文本的属性。

我想从后面的代码中动态添加具有相同结构的GridViewColumns,但是我找不到将ItemSource和ItemSource添加到DataTemplate的方法。我该怎么办?

c# wpf xaml code-behind
2个回答
0
投票

您可以使用FrameworkElementFactory将数据模板添加到单元模板,并且此示例也适用于将DataTemplate添加到ItemTemplate:

© www.soinside.com 2019 - 2024. All rights reserved.