How to change the Border Background Color in a ItemContainerStyle programmatically?

9.6k views Asked by At

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:

Shell.xaml

    <TreeView DockPanel.Dock="Bottom" Name="lstDbTree"
      ...
      ItemContainerStyle="{StaticResource DbTreeItemStyle}"
      ...
    />

CoreStyles.xaml

    <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

Shell.xaml.cs

    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"));
    }

What I want to do

enter image description here

Thank's a lot for any Help.

1

There are 1 answers

0
Dirk Schiller On

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"));
    }