WPF - XAML Treeview 到 Generic.List 绑定
我正在尝试将 IList 绑定到分层显示中的 WPF TreeView。这是我的对象:
public class TeamsTreeViewItem
{
public string DisplayValue { get; set; }
public string KeyValue { get; set; }
readonly List<TeamsTreeViewItem> children = new List<TeamsTreeViewItem> ();
public IList<TeamsTreeViewItem> Children
{
get
{
return children;
}
}
public override string ToString ()
{
return DisplayValue;
}
}
我不知道一个特定对象将有多少个子对象,并且这些子对象也可能有子对象。
我正在忙着我的 HierarchialDataTemplate,但没有成功:
<TreeView Canvas.Left="263" Canvas.Top="12" Height="200" Name="TeamTreeView" Width="120">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:TeamsTreeViewItem}" ItemsSource="{Binding DisplayValue}" >
<TextBlock Text="{Binding DisplayValue}"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:TeamsTreeViewItem}" ItemsSource="{Binding Children}" >
<TextBlock Text="{Binding DisplayValue}"/>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
有什么建议吗?
I am trying to bind an IList to a WPF TreeView in a hierarchal display. Here is my object:
public class TeamsTreeViewItem
{
public string DisplayValue { get; set; }
public string KeyValue { get; set; }
readonly List<TeamsTreeViewItem> children = new List<TeamsTreeViewItem> ();
public IList<TeamsTreeViewItem> Children
{
get
{
return children;
}
}
public override string ToString ()
{
return DisplayValue;
}
}
I don't know how many children a particular object will have, and the children might have children too.
I am fussing around with my HierarchialDataTemplate, but not being successful:
<TreeView Canvas.Left="263" Canvas.Top="12" Height="200" Name="TeamTreeView" Width="120">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:TeamsTreeViewItem}" ItemsSource="{Binding DisplayValue}" >
<TextBlock Text="{Binding DisplayValue}"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:TeamsTreeViewItem}" ItemsSource="{Binding Children}" >
<TextBlock Text="{Binding DisplayValue}"/>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要将 ItemsSource 应用于子级,如下所示:
我基于 DataType 应用了此 DataTemplate,这样,如果子级具有相同类型 (TeamsTreeViewItem),则应自动将其应用于它找到的该类型的任何项目,即使它是一个孩子、孙子或曾曾曾....孙子。只需确保包含定义 TeamsTreeViewItem 的命名空间(此处表示为“本地”)即可。
You need to apply the ItemsSource to the children like so:
I applied this DataTemplate based on the DataType, that way if the children are of the same type (TeamsTreeViewItem) is should automatically apply it to any item it finds of that type, even if it is a child, grandchild, or great great great .... grandchild. Just make sure to include the namespace (denoted here as "local") that the TeamsTreeViewItem is defined in.