You need to change the ItemContainerStyle
of the TreeView
in xaml. Bind the Background
property to a string property in the item view model and use a converter to convert that string property into a Brush
. You can then set the background from the view model when the IsSelected
property is set. Here are some code snippets that may be useful.
<treeview.itemcontainerstyle>
<style targettype="{x:Type TreeViewItem}">
<setter property="Background" value="{Binding BackgroundColour, Converter={StaticResource BackgroundToColourConverter},Mode=OneWay}" />
<setter property="IsExpanded" value="{Binding IsExpanded, Mode=TwoWay}" />
<setter property="IsSelected" value="{Binding IsSelected, Mode=TwoWay}" />
</style>
</treeview.itemcontainerstyle>
public class BackgroundToColourConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
string s = value as string;
Color color;
switch (s)
{
case "Green":
color = Colors.Green;
break;
case "Red":
color = Colors.Red;
break;
default:
color = Colors.White;
break;
}
return new SolidColorBrush(color);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}