I have a TreeView and it's own Style and it's own ItemContainerStyle. In the ItemContainerStyle I have a Border with the Name "SelectedRectangle". Now I want to change the Background Color of this "SelectedRectangle" by using this Code (I found it in the Internet):
Border brd = (Border)lstDbTree.Template.FindName("SelectedRectangle", lstDbTree); //dosnt work - returns 'null'
brd.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#7B7A7C")); // Null Pointer Exception
I don't know how I can get access to the ItemContainerStyle XAML to manipulate it programmatically.
The Code:
<TreeView DockPanel.Dock="Bottom" Name="lstDbTree"
...
ItemContainerStyle="{StaticResource DbTreeItemStyle}"
...
/>
<Style TargetType="TreeViewItem" x:Key="DbTreeItemStyle">
<Setters...>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TreeViewItem">
...
<Border x:Name="SelectedRectangle" BorderBrush="#44ffffff" BorderThickness="1" Grid.Column="1" CornerRadius="1" IsHitTestVisible="False" Opacity="0" Background="#555355"/>
...
</ControlTemplate>
</Setter.Value>
</Style
private void ColorB_OnClick(object sender, RoutedEventArgs e)
{
Border brd = (Border)lstDbTree.Template.FindName("SelectedRectangle", lstDbTree); //dosnt work
brd.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#7B7A7C"));
}
Thank's a lot for any Help.
I could fix this Issue with the ItemContainerGenerator:
private void ColorB_OnClick(object sender, RoutedEventArgs e)
{
//TODO: Do this for all Items and not only for the "Selected Item"
TreeViewItem tvi = lstDbTree.ItemContainerGenerator.ContainerFromItem(lstDbTree.SelectedItem) as TreeViewItem;
Border brd = (Border)tvi.Template.FindName("SelectedRectangle", tvi);
brd.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#7B7A7C"));
}