我应该采取什么方法将数据绑定到 TreeView?
我有一个架构师问题:
我想使用树视图显示一些类别,并且如果用户单击每个类别,则需要显示该类别的总产品。
我需要采取什么方法?
目前,我正在尝试做: 1)从数据库获取数据并将其加载到DataTable,并且DataTable可以从xaml访问。 2)从xaml调用DataTable并从dataTable Column绑定TreeViewItem...即,
<TreeView ItemsSource="{Binding ElementName=_this, Path=SubCategoriesTable}" Name="trSubCategories">
<TreeView.ItemTemplate>
<DataTemplate>
<TreeViewItem Header="Home">
<TreeViewItem Header="{Binding Path=sub_category_name}"></TreeViewItem>
</TreeViewItem>
</DataTemplate>
</TreeView.ItemTemplate>
我不知道这是一个正确的方法吗?或者我应该通过循环遍历每个数据表行和列来在后面的代码中添加 TreeViewItem 吗?
请帮忙!
I have an architect question:
I want to use Tree View to display some categories and on each categories if user clicks, need to show total product for that category.
What approach do I need to take?
Currently, I am trying to do:
1) Get Data from Database and load it to DataTable and DataTable is accessable from xaml.
2) Calling DataTable from xaml and binding TreeViewItem from dataTable Column...i.e.,
<TreeView ItemsSource="{Binding ElementName=_this, Path=SubCategoriesTable}" Name="trSubCategories">
<TreeView.ItemTemplate>
<DataTemplate>
<TreeViewItem Header="Home">
<TreeViewItem Header="{Binding Path=sub_category_name}"></TreeViewItem>
</TreeViewItem>
</DataTemplate>
</TreeView.ItemTemplate>
I don't know is it a right approach to go? Or Should I add TreeViewItem in my code behind by looping though each datatable row and column?
Please help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 HierarchicalDataTemplate 并绑定您的
TreeView< /code> 相应地。您可以使用任何对象类型作为绑定的支持;它不需要是
DataTable
。您应该避免在后面的代码中构建
TreeViewItem
。它根本不需要,并且使下游管理比需要的更加麻烦。正如 ChristopherS 所指出的; Josh Smith 有一篇关于TreeView with MVVM 的精彩文章。 Bea Stoliz 还有一篇关于在 TreeView 中显示分组数据的精彩帖子。
Use a HierarchicalDataTemplate and bind your
TreeView
accordingly. You can use any object type as the backing for the binding; it doesn't need to be aDataTable
.You should avoid building out
TreeViewItem
's in your code behind. It is simply not needed and makes down stream management more cumbersome then it needs to be.As noted by ChristopherS; Josh Smith has an excellent article on a TreeView with MVVM. Bea Stoliz also has a nice post on displaying grouped data in a TreeView.
这可能是到目前为止您可以找到的有关此主题的最佳教程:http://www.codeproject.com/KB/WPF/TreeViewWithViewModel.aspx
This is probably by far the best tutorial you can find about this topic: http://www.codeproject.com/KB/WPF/TreeViewWithViewModel.aspx