简体   繁体   English

WPF TreeView不会相应地应用DataTemplate

[英]WPF TreeView does not apply DataTemplate accordingly

I have a business object project, which contains composite structure: 我有一个业务对象项目,其中包含复合结构:

public class Tree 
{ public IProductComponent TreeRoot { get; set; } }

public interface ITreeComponent 
{ public string Name { get; set; } }

public class ContainerComponent : ITreeComponent
{ public BindingList<ITreeComponent> Children { get; set; } }

public class LeafComponent : ITreeComponent
{ }

I need to bind this structure to a TreeView in my WPF project. 我需要将此结构绑定到WPF项目中的TreeView。 The tree view first: 首先是树视图:

<TreeView x:Name="treeView" Grid.ColumnSpan="2">
 <TreeView.Resources>
  <HierarchicalDataTemplate 
   ItemsSource="{Binding Children}" 
DataType="{x:Type businessObjects:ContainerComponent}">
   <Label Content="{Binding Name}"/>
  </HierarchicalDataTemplate>
  <DataTemplate DataType="{x:Type businessObjects:LeafComponent}">
   <Label Content="{Binding Name}"/>
  </DataTemplate>
 </TreeView.Resources>
</TreeView>

And the code for binding: 和绑定代码:

bTreeView = new Binding();
bTreeView.Source = MyTree;
bTreeView.Path = new PropertyPath("TreeRoot.Children");
treeView.SetBinding(TreeView.ItemsSourceProperty, bTreeView);

The problem is that the TReeView does not actually use those templates (it displays only the top level of hierarchy and calls .ToString() to display those items. Please tell me where have I gone wrong. Otherwise, if I set the it is working, but I cannot define two templates there. 问题在于TReeView实际上并未使用这些模板(它仅显示层次结构的顶层,并调用.ToString()来显示这些项目。请告诉我哪里出了问题。否则,如果我将其设置为有效,但是我不能在那里定义两个模板。

Thanks. 谢谢。

Well I notice you are putting the template in resources, not under TreeVeiw.ItemTemplate. 好吧,我注意到您将模板放在资源中,而不是在TreeVeiw.ItemTemplate下。

TreeView should have an ItemTemplate (the Hierarchical) and the ItemsSource set. TreeView应该具有一个ItemTemplate(层次结构)和ItemsSource集。 Shouldn't need anything more than that. 不应只需要这些。

Would help with example data for us to test though. 虽然可以帮助我们进行示例数据测试。

My bad - the Main assembly was loading the dll with entities two times instead of one. 我的错-主程序集向dll加载实体而不是两次。 That caused it to go crazy - as soon as I fixed it and the assembly loaded once the problems went away. 这使它发疯了-一旦问题解决,我一修复它,然后装入程序集。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM