[英]WPF Programmatically create treeview itemtemplate/columns
I have an application that reads database tables and puts it into a treeview.我有一个读取数据库表并将其放入 treeview 的应用程序。 The current ItemTemplate for the treeview looks like this:
treeview 的当前 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>
However, in the future there could be more columns that need to be added (determined by the number of distinct values in a table), so I'm trying to create it dynamically.但是,将来可能需要添加更多列(由表中不同值的数量确定),因此我尝试动态创建它。 How would I go about doing that?
我将如何 go 这样做?
Something like this might be possible:这样的事情可能是可能的:
<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>
It depends if the DataContext of the TreeViewItem (the SubOrganLocation) can expose a collection of fields, or at least be used to derive them with a converter.这取决于 TreeViewItem(SubOrganLocation)的 DataContext 是否可以公开字段集合,或者至少用于通过转换器派生它们。 The simplest and probably easiest would be to expose a collection of fields so you can just do
{Binding Fields}
.最简单且可能最简单的方法是公开一组字段,以便您可以执行
{Binding Fields}
。
As FlyingStreudel said, using custom controls is a good approach in this case.正如 FlyingStreudel 所说,在这种情况下使用自定义控件是一种很好的方法。 The XAML would look something like:
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>
You don't have to use custom controls, you can put your specific columns in each template.您不必使用自定义控件,您可以将特定列放在每个模板中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.