Sunday, May 20, 2007

Create editable TreeViewItem using styles

One of clients asked me a question: "How easily create editable TreeViewItem". I answers: "Simple. Just use styles, triggers and templates." Let's start. We need something like this.

image

First of all, let's create simple tree with data, provided by XmlDataSource.  Something like this will be good enough

<root>
<
leaf id="1" name="leaf1">
<
group id="1" name="group1">
<
item name="item1" id="1">
<
subitem id="1">test 1</subitem>
<
subitem id="5">test 2</subitem>
<
subitem id="5">test 3</subitem>
<
subitem id="5">test 4</subitem>
<
subitem id="5">test 5</subitem>
</
item>

 


Next step is to create HierarchicalDataTemplate. Just for fun, let's do it dummy way :)


<HierarchicalDataTemplate DataType="leaf" ItemsSource ="{Binding XPath=*}">
<
TextBlock Text="{Binding XPath=@name}" />
</
HierarchicalDataTemplate>
<
HierarchicalDataTemplate DataType="group" ItemsSource ="{Binding XPath=*}">
<
TextBlock Text="{Binding XPath=@name}" Foreground="Blue" />
</
HierarchicalDataTemplate>
<
HierarchicalDataTemplate DataType="item" ItemsSource ="{Binding XPath=*}">
<
TextBlock Text="{Binding XPath=@name}" Foreground="Red"/>
</
HierarchicalDataTemplate>
</
Window.Resources>

 


Next, I want to replace TextBlock inside node with editable TextBox, but only when I have no items inside. It's possible to do it "smart way", by creating ControlTemplates of HeaderedItemControl, that looks if it has items inside and choose wherever it need to choose, But the original question was "how to do it simple way". So, we'll create data template for it


<DataTemplate x:Key="editableName">
<
TextBox Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=HeaderedItemsControl}, Path=(Header).InnerText}"/>
</
DataTemplate>

 


How, what we have here? In order to show current data inside the TextBox text, we have to bind it to the ancestor's header. Actually it's XmlElement in our case, to we have to get InnerText property of the node. Simple - isn't it? BTW, you can find Ancestor type of TreeViewItem - result will be exactly the same.


The last step - create a style, that has trigger for IsSelected property of TreeViewItem and change a template. Really, simple


<Style TargetType="TreeViewItem">
<
Style.Triggers>
<
Trigger Property="IsSelected" Value="True">
<
Setter Property="HeaderTemplate" Value="{StaticResource editableName}" />
</
Trigger>
</
Style.Triggers>
</
Style>

 


Now, I have a homework for you - create the same thing for those TreeViewItems, which has Items inside them. This is the clue, that might help you.


image


Source code for this article

No comments: