c# WPF管理树视图项模板
本文关键字:视图 WPF 管理 | 更新日期: 2023-09-27 18:01:51
也许这是一个安静简单的问题,但我有一个问题,为我的树视图模板的建设。我有一些课程:
public class A //main class
{
public B sth { get; set; }
public C sthelse { get; set; }
public A()
{
this.sth = new B(1000, "sth");
this.sthelse = new C();
}
}
public class B
{
public D sth { get; set; }
public B(ulong data, String abc)
{
this.sth = new D(data, abc);
}
}
public class D
{
public ulong data { get; private set; }
public String abc { get; private set; }
public D(ulong data, String abc)
{
this.data = data;
this.abc = abc;
}
}
我的问题是如何把它放到treeview中。我正在测试HierarchicalDataTemplate,但问题是,它必须绑定到集合。你知道如何创建这样的treeview吗?
- 一
- B
- D
- abc
C - D
- B
有可能吗?
我正在使用这个代码:
<TreeView ItemsSource="{Binding}" ItemTemplate="{StaticResource phy}" />
<Window.Resources>
<DataTemplate x:Key="d">
<StackPanel Orientation="Vertical">
<!-- Maybe there should be pairs property - value, maybe grid or whatever -->
<TextBlock Text="{Binding Path=data}" />
<TextBlock Text="{Binding Path=abc}" />
</StackPanel>
</DataTemplate>
<HierarchicalDataTemplate x:Key="b" ItemsSource="{Binding Path=sth}" ItemTemplate="{StaticResource ResourceKey=d}">
<TextBlock Text="D" />
</HierarchicalDataTemplate>
<!-- Cant bind also attribute C -->
<HierarchicalDataTemplate x:Key="phy" ItemsSource="{Binding Path=sth}" ItemTemplate="{StaticResource ResourceKey=b}">
<TextBlock Text="PHY" />
</HierarchicalDataTemplate>
</Window.Resources>
在代码中是:
public ObservableCollection<A> data { get; private set; }
在构造函数中:
data = new ObservableCollection<A>();
treeView1.DataContext = data;
data.Add(new A());
ItemsSource
属性值必须为IEnumerable
。这是无法避免的。你可以用一种非常简单的方式暴露IEnumerables
,如下所示,但我建议使用比这更好的对象模型。您可以使用这些类并将树的ItemsSource
属性和HierarchicalDataTemplate
属性绑定到这个新的Nodes
属性。
public class A //main class
{
public B sth { get; set; }
public C sthelse { get; set; }
public A()
{
this.sth = new B(1000, "sth");
this.sthelse = new C();
}
public IEnumerable<object> Nodes
{
get
{
yield return B;
yield return C;
}
}
}
public class B
{
public D sth { get; set; }
public B(ulong data, String abc)
{
this.sth = new D(data, abc);
}
public IEnumerable<object> Nodes
{
get
{
yield return D;
}
}
}
public class D
{
public ulong data { get; private set; }
public String abc { get; private set; }
public D(ulong data, String abc)
{
this.data = data;
this.abc = abc;
}
public IEnumerable<object> Nodes
{
get
{
yield return data;
yield return abc;
}
}
}