WPF 树视图问题
是否可以在 TreeView 控件的每个项目中存储一些数据?我的意思是,除了标题文本之外,还有一些有用的东西(例如字符串)? 谢谢。
Is it possible to store some data in every item of a TreeView control? I mean, something useful (e.g. a string) besides the header text?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,WPF 是“无外观”的,因此您的实际数据可以是您想要的任何数据,而
TreeView
只是一个用于向用户显示数据的Template
以预定的方式。您可以将该
Template
的任何部分覆盖为您想要的任何内容,和/或将其绑定到您的数据。编辑
我不是使用 TreeView 的专家,但是如果您有一个
List
的 DataContext,并且每个Folder
对象都有一个Name
和FullPath
属性,您的 TreeView 可能看起来像这样:如果您还没有,我强烈建议您在使用 WPF 时研究 MVVM 设计模式。基本上,您的应用程序就是您的类(ViewModel),而控件/XAML(视图)只是一个位于类之上的漂亮层,使它们对用户友好。
从 WinForms TreeView 切换到 WPF TreeView 时,这是一个重要概念
Yes, WPF is "lookless", so your actual data can be anything you want it to be, and a
TreeView
is just aTemplate
used to display the data to the user in a pre-determined way.You can overwrite any part of that
Template
to be whatever you want, and/or have it bind to your data however you want.Edit
I'm no expert on using the TreeView, but if you had a DataContext of
List<Folder>
, and eachFolder
object had aName
and aFullPath
property, your TreeView could look something like this:If you haven't already, I'd highly recommend looking into the MVVM design pattern when working with WPF. Basically your application is your classes (ViewModels), and the Controls/XAML (Views) are just a pretty layer that sits on top of your classes to make them user-friendly.
This is an important concept when switching from a WinForms TreeView to a WPF TreeView
这取决于您所说的存储数据的含义...
如果您只是谈论 UI 定制,Rachel 的上述答案是有效的。
如果您正在讨论存储任意对象值,例如有关 TreeViewItem 的信息,或者可能是两个项目之间的关系,则可以使用 TreeViewItem 的 Tag 属性。例如,我必须编写一个映射 UI,其中两棵树链接在一起,其中第一棵树的每个 TreeViewItem 可以连接到第二棵树的 1 个 TreeViewItem。我使用第一个 TreeViewItem 的 Tag 属性来存储连接的 TreeViewItem。
It depends on what you mean by store data...
If you're just talking UI customization Rachel's answer above works.
If you're talking about storing arbitrary object values, such as information about the TreeViewItem, or maybe a relation between two items, you can use the Tag property of TreeViewItem. For example, I had to write a mapping UI where two trees linked together where each TreeViewItem from the first tree, could connect to 1 TreeViewItems of the second tree. I used the Tag property of the first TreeViewItem to store the connecting TreeViewItem.