0

I want in the loop for each Node be able to change Background in Stack Panel when the Node accessed and after it left set Background to Transparent again.

My problem: I do not know how to access to Stack Panel to change BackGround from code behind. I would appreciate any help

Here is my code: TreeView Control

<TreeView Grid.Column="1" Grid.Row="0" ItemsSource="{Binding ListOfNodes}"
                                                    Background="Linen" Margin="0,0,0,-0">
    <TreeView.ItemContainerStyle>
        <Style TargetType="{x:Type TreeViewItem}">
            <Setter Property="IsExpanded" Value="True"/>
        </Style>
    </TreeView.ItemContainerStyle>
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate x:Name="HDT_node" DataType="Node" ItemsSource="{Binding Children}">
            <StackPanel Orientation="Horizontal"
                                    MouseLeftButtonDown="btnTreeItemStartPlay"
                                    Background="Transparent">
                <Image Source="{Binding Path=image.Source}" Width="30" Height="30"
                                HorizontalAlignment="Left"
                                     MouseEnter="ZoomStart" MouseLeave="ZoomStop" />
            </StackPanel>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

Class Node:

public class Node
{
    public Image image { get; set; }

    public List<Node> Children { get; set; }

    public Node()
    {
    }

    public Node(Image imageIn, int orderIndexIn)
    {
        image = imageIn;
        Children = new List<Node>();
    }
}
Red
  • 2,728
  • 1
  • 20
  • 22
Yefim
  • 11
  • 2
  • Similar to this: http://stackoverflow.com/questions/34117944/listbox-items-return-string-when-datatemplate-is-button – Salah Akbari Apr 08 '16 at 20:35

1 Answers1

1

There is no direct way to access StackPanel within DataTemplate. However you can still use VisualTreeHelper to iterate over visual tree on runtime and do whatever you want to do.

Before doing that use WPF Visual Tree Visualizer to familiarize yourself with Visual Tree that you have. Afterward start from TreeView and iterate over children to get desired child. As based on your templates, visual tree varies.

Adnan Umer
  • 3,669
  • 2
  • 18
  • 38