【发布时间】:2021-12-19 00:10:53
【问题描述】:
我有一个遵循复合设计模式的对象。我想使用树视图在 WPF 中显示此对象,但我无法正确绑定数据。我有两个类:Leaf,没有任何子元素的简单类,和 Box,具有子元素的复合类,可以是 Box 类的 Leaf 类。我还有一个名为 ITree 的通用接口
界面
public interface ITree
{
string Name { get; }
string Property1 { get; }
string Property2 { get; }
}
简单类
public class Leaf : ITree
{
string ITree.Name { get { return _name; } }
string ITree.Property1 { get { return property1; } }
string ITree.Property2 { get { return property2; } }
}
复合类
public class Box : ITree
{
string ITree.Name { get { return _name; } }
string ITree.Property1 { get { return property1; } }
string ITree.Property2 { get { return property2; } }
List<ITree> Children = new List<ITree>();
}
xaml.cs
List<ITree> ListToBind = new List<ITree>();
ITree finalObject = PopulateCompositeObjeectWithData();
ListToBind.Add(finalObject);
xaml
<TreeView ItemsSource="{Binding ElementName=Window, Path= ListToBind}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<TextBlock Text="{Binding Name}"/>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
我想要实现的树视图:
Box - Name
|-Leaf - Name
|-Leaf - Name
|-Box - Name
| |-Leaf - Name
| |-Leaf - Name
任何建议或代码示例将不胜感激
谢谢
【问题讨论】:
标签: wpf data-binding treeview composite