WPF以编程方式创建树视图项目模板/列

问题描述

| 我有一个读取数据库表并将其放入树状视图的应用程序。树视图的当前ItemTemplate如下所示:
<TreeView.ItemTemplate>
    <HierarchicalDataTemplate ItemsSource=\"{Binding SubOrganLocations}\">
        <Grid>
            <Grid.ColumnDeFinitions>
                <ColumnDeFinition Width=\"*\" />
                <ColumnDeFinition Width=\"35\" />
                <ColumnDeFinition Width=\"35\" />
                <ColumnDeFinition Width=\"35\" />
            </Grid.ColumnDeFinitions>
            <TextBlock Grid.Column=\"0\" Text=\"{Binding OrgandisplayName}\" />
            <TextBox Grid.Column=\"1\" IsEnabled=\"True\" />
            <TextBox Grid.Column=\"2\" IsEnabled=\"True\" />
            <TextBox Grid.Column=\"3\" IsEnabled=\"True\" />
        </Grid>
    </HierarchicalDataTemplate>
</TreeView.ItemTemplate>
但是,将来可能需要添加更多列(由表中不同值的数量确定),因此我尝试动态创建它。我将如何去做?     

解决方法

这样的事情可能是可能的:
<TreeView.ItemTemplate>
    <HierarchicalDataTemplate ItemsSource=\"{Binding SubOrganLocations}\">
        <StackPanel Orientation=\"Horizontal\">
                <TextBlock Text=\"{Binding OrganDisplayName}\" />

                <!-- If the fields to bind to can be exposed via a collection:
                <ItemsControl ItemsSource=\"{Binding Fields}\"> -->
                <ItemsControl ItemsSource=\"{Binding,Converter={StaticResource SomeCleverConverter}}\">
                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <StackPanel Orientation=\"Horizontal\" />
                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <TextBox Text=\"{Binding Value}\" Width=\"35\" />
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>

            </StackPanel>
    </HierarchicalDataTemplate>
</TreeView.ItemTemplate>
这取决于TreeViewItem的DataContext(SubOrganLocation)是否可以公开字段的集合,或者至少用于通过转换器派生它们。最简单而且可能最简单的方法是公开一个字段集合,以便您可以执行do2ѭ。     ,正如FlyingStreudel所说,在这种情况下,使用自定义控件是一种很好的方法。 XAML看起来像:
        <!-- entity 1 -->
        <HierarchicalDataTemplate DataType=\"{x:Type local:Entity1}\" ItemsSource=\"{Binding Items,Mode=OneWay}\">
            <Grid>
                <local:Entity1Control/>
            </Grid>
        </HierarchicalDataTemplate>

        <!-- entity 2 (leaf) -->
        <DataTemplate DataType=\"{x:Type local:Entity2}\">
            <Grid>
                <local:Entity2Control />
            </Grid>
        </DataTemplate>
您不必使用自定义控件,可以在每个模板中放入特定的列。