Page 1 of 1

How to set 2 color background to a TreeView

Posted: 23 Jan 2025, 11:19
by Logrus
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?

Re: How to set 2 color background to a TreeView

Posted: 24 Jan 2025, 11:22
by sfernandez
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>

Re: How to set 2 color background to a TreeView

Posted: 24 Jan 2025, 15:23
by Logrus
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.

Re: How to set 2 color background to a TreeView

Posted: 24 Jan 2025, 21:07
by KeldorKatarn
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

Re: How to set 2 color background to a TreeView

Posted: 27 Jan 2025, 18:07
by Logrus
When it doubt.. Behavior ;) Works almost always for these kinds of things in XAML
That's for sure

Re: How to set 2 color background to a TreeView

Posted: 30 Jan 2025, 13:00
by sfernandez
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!