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

本文关键字:视图 编程 方式 创建 WPF | 更新日期: 2023-09-27 17:57:41

我有一个应用程序,它读取数据库表并将其放入树视图中。树视图的当前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>

但是,将来可能会有更多的列需要添加(由表中不同值的数量决定),所以我尝试动态创建它。我该怎么做呢?

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

类似的事情可能发生:

<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(SubOrganLocation)的DataContext是否可以公开字段集合,或者至少用于通过转换器派生字段。最简单也可能最简单的方法是公开一个字段集合,这样您就可以只执行{Binding Fields}

正如FlyingTreudel所说,在这种情况下,使用自定义控件是一种很好的方法。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>

您不必使用自定义控件,可以在每个模板中放置特定的列。