I have a requirement that , i need to add nodes to 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
I have a requirement that , i need to add nodes to 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:
Children
property of type ObservableCollection<CheckableItem>
.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:
<HierarchicalDataTemplate
DataType="{x:Type local:CheckableItem}"
ItemsSource="{Binding Children}">
<StackPanel Orientation="Horizontal">
<Checkbox IsChecked="{Binding IsChecked}"/>
<TextBlock Text="{Binding Value}/>
</StackPanel>
</HierarchicalDataTemplate>
...and a TreeView
that uses it (I'm assuming you've populated a collection of these objects, of course):
<TreeView ItemsSource="{Binding MyCollectionOfCheckableItems}"/>
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 CheckableItem
s, are turned into TreeViewItem
s 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.