如何解决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>
您不必使用自定义控件,可以在每个模板中放入特定的列。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。