Let’s look at another often used control in business applications – TreeView. It is a great control to visualise hierarchical data. Take an example – of customer, their orders and order details. A lot of data without using TreeView – it can get little bit complex to show the relationship between the data.
Just like we have ListBox and its ListBoxItem where we can include any control – not just text; we have TreeView has TreeViewItem.
The XAML goes as:
<TreeView Margin="10,10"><TreeViewItem Header="Sony"><TreeViewItem Header="Order-123"><TreeViewItem Header="LCD TV"/><TreeViewItem Header="Wii"/><TreeViewItem Header="Vaio"/></TreeViewItem></TreeViewItem><TreeViewItem Header="Apple"><TreeViewItem Header="Order-1"><TreeViewItem Header="iPod"/><TreeViewItem Header="iPhone"/><TreeViewItem Header="iPad"/></TreeViewItem><TreeViewItem Header="Order-2"><TreeViewItem Header="Mac"/></TreeViewItem></TreeViewItem></TreeView>
Not the best data, but I hope good enough to use in a TreeView.
The output is:
How do we add items in code? We have instantiate TreeViewItem objects and add it to the “Items” collection. For e.g.:
TreeViewItem item = new TreeViewItem();item.Header = "1";item.Items.Add(new TreeViewItem { Header = "10" });item.Items.Add(new TreeViewItem { Header = "11" });item.Items.Add(new TreeViewItem { Header = "12" });TreeViewItem item2 = new TreeViewItem();item2.Header = "2";item2.Items.Add(new TreeViewItem { Header = "20" });item2.Items.Add(new TreeViewItem { Header = "21" });item2.Items.Add(new TreeViewItem { Header = "22" });tv.Items.Add(item);tv.Items.Add(item2);
Now we have set the Foreground colour of Window class to Orange – but we do not get Orange on the TreeView text Why?
You will see that when a TreeViewItem is selected, its foreground colour turns to White and background to blue.
So if the ‘White’ foreground colour inherits down to the other TreeViewItems – then their fore colour will also change to White – making then invisible.
To test this, let’s add a TextBlock as a child without using TreeViewItem:
<TreeViewItem Header="Order-1"><TreeViewItem Header="iPod"/><TreeViewItem Header="iPhone"/><TreeViewItem Header="iPad"/><TextBlock Text="Apple TV" /></TreeViewItem>
As you can see here, a TextBlock inherits its foreground colour from its parent – ‘Order-1’ TreeViewItem – and so appears to be hidden. This means that each TreeViewItem uses system settings for their colour settings – when selected. So:
- When we are using TreeViewItem, the property values are not inherited from parent
- When using controls directly, property values are inherited
So how do we set a common foreground for all the TreeViewItems?
Wow, you have a copywriting talent.
ReplyDeleteI've passed dozens of tutorials on WPF TreeView and this is the best - most simple, step by step, reproducible
You made my day.
ReplyDeleteThank you!