Good question, because this technique is very important, because default coloring of framework elements used as tree nodes is quite ugly, so you need such code in many cases.
Let's assume you use
TextBlock
for your selectable items, also assume that the
TextBlock
has default black-on-white colors (or set all those colors programmatically when a new item is added to be in sync with selected/deselected colors use below):
lblDetailTree.SelectedItemChanged += (sender, eventArgs) => {
TextBlock oldItem = eventArgs.OldValue as TextBlock;
TextBlock newItem = eventArgs.NewValue as TextBlock;
if (oldItem != null) {
oldItem.Background = Brushes.White;
oldItem.Foreground = Brushes.Black;
}
if (newItem != null) {
newItem.Background = Brushes.CadetBlue;
newItem.Foreground = Brushes.Yellow;
}
};
Tested:
CadetBlue
does not look so nice, try
Navy
:-).
You cannot use strings as nodes (there is nothing to paint in this object :-)). Because of a very flexible content model of WPF, writing this effect for polymorphous objects or universal code insensitive to the node type is a bit difficult. For example, using direct base class of
TextBlock
is not possible, because this is
FrameworkElement
, which does not have
Background
or
Foreground
property, so, it you use a combination of controls and other framework elements, you will need to make a separate cast/check for every
FrameworkElement
-based class which is not
Control
and one for all
Control
-based classes.
—SA