Logrus
Topic Author
Posts: 64
Joined: 22 Jul 2015, 12:16

How to set 2 color background to a TreeView

23 Jan 2025, 11:19

Hi,
        <AlternationConverter x:Key="Converter.AlternationRows">
            <SolidColorBrush>#00333333</SolidColorBrush>
            <SolidColorBrush>#FF282828</SolidColorBrush>
        </AlternationConverter>

        <Style TargetType="TreeViewItem">
            <Setter Property="AlternationCount" Value="2"/>
            <Setter Property="Background" 
                          Value="{Binding Path=(ItemsControl.AlternationIndex), 
                          RelativeSource={RelativeSource Self}, Converter={StaticResource Converter.AlternationRows}}" />
        </Style>

       <TreeView AlternationCount="2"/>
It's not working the way I expect it to. Each nested TreeViewItem starts with AlternationIndex = 0.

Can you tell me how to implement indexing of all expanded TreeViewItems?
 
User avatar
sfernandez
Site Admin
Posts: 3197
Joined: 22 Dec 2011, 19:20

Re: How to set 2 color background to a TreeView

24 Jan 2025, 11:22

As the TreeView is a hierarchical control, each child has its own Items collection with different indices. If you have to use a TreeView, the AlternationIndex is not an option here, you might want to expose a global index in your item view model instead.
<Style TargetType="TreeViewItem">
  <Setter Property="AlternationCount" Value="2"/>
  <Setter Property="Background" 
          Value="{Binding ItemIndex, Converter={StaticResource Converter.AlternationRows}}"/>
</Style>
 
Logrus
Topic Author
Posts: 64
Joined: 22 Jul 2015, 12:16

Re: How to set 2 color background to a TreeView

24 Jan 2025, 15:23

I have implemented a Behavior that attaches to the TreeViewItem and
recalculates the AlternationIndex with the Expanded State of the TreeViewItem.

The Behavior handles Loaded, Expanded, and Collapsed.
 
KeldorKatarn
Posts: 234
Joined: 30 May 2014, 10:26

Re: How to set 2 color background to a TreeView

24 Jan 2025, 21:07

I have implemented a Behavior that attaches to the TreeViewItem and
recalculates the AlternationIndex with the Expanded State of the TreeViewItem.

The Behavior handles Loaded, Expanded, and Collapsed.
When it doubt.. Behavior ;) Works almost always for these kinds of things in XAML
 
Logrus
Topic Author
Posts: 64
Joined: 22 Jul 2015, 12:16

Re: How to set 2 color background to a TreeView

27 Jan 2025, 18:07

When it doubt.. Behavior ;) Works almost always for these kinds of things in XAML
That's for sure
 
User avatar
sfernandez
Site Admin
Posts: 3197
Joined: 22 Dec 2011, 19:20

Re: How to set 2 color background to a TreeView

30 Jan 2025, 13:00

I have implemented a Behavior that attaches to the TreeViewItem and
recalculates the AlternationIndex with the Expanded State of the TreeViewItem.

The Behavior handles Loaded, Expanded, and Collapsed.
That is a good solution too, thanks for sharing it!

Who is online

Users browsing this forum: No registered users and 0 guests