wpf 带复选框的treeview,如何在WPF中使用复选框开发TreeView?

I have a requirement that , I need to add nodes to a TreeView dynamically and that nodes with CheckBoxes. If one CheckBox is selected childs also selected.

And mainly I want to add data to TreeView dynamically.

解决方案

This is remarkably straightforward to do, once you know how.

Create a view model class (I've called it CheckableItem here) for your tree view item data. It needs these three things:

It must implement INotifyPropertyChanged.

It needs a Children property of type ObservableCollection.

It needs an IsChecked property of type Visibility that, in its setter, raises PropertyChanged and also iterates through the items in Children and sets their IsChecked property.

Implement other properties in this class to expose the items' data to binding (my example just assumes something called Value). Or you can just implement an Item class of type object and use a ContentPresenter in the template, but I'll leave figuring that out to you.

Now create a HierarchicalDataTemplate for your class that looks something like this:

DataType="{x:Type local:CheckableItem}"

ItemsSource="{Binding Children}">

...and a TreeView that uses it (I'm assuming you've populated a collection of these objects, of course):

How it works: The TreeView uses the HierarchicalDataTemplate to render each item in its ItemsSource. The HierarchicalDataTemplate is a template that creates a HeaderedItemsControl (in this case a TreeViewItem), uses its template to render the header, and then uses its ItemsSource as the source for the control's items - which, since they're all CheckableItems, are turned into TreeViewItems by the HierarchicalDataTemplate. After that, it's turtles all the way down.

This is a pretty good overview of how TreeView actually works in practice, though as with most examples I've found, it's got so many bells and whistles that it's sort of hard to see how simple the underlying principles are. If you understand MVVM, the previous paragraph is 90% of what you need to know.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值