0
votes

I have a treeview control that picks item controls dynamically through a template selector. I have bound the property IsExpanded on my model to IsExpanded on TreeViewItem using a Setter. (I know this is hooked up, because if I set IsExpanded to true in the model constructor, the entire tree is expanded, as expected.)

Here's the problem. After the I load the tree, just the root node is visible (as expected), but if I set IsExpanded on a node to true, the tree is supposed to expand to the node that changed, but it does not. (I've put debug markers in to make sure the property is actually changing. )

Here is my xaml:

<Window.Resources>
    <HierarchicalDataTemplate x:Key="RegularNodeTemplate" 
        ItemsSource="{Binding Path=Children}" >
        <StackPanel Orientation="Horizontal">
            <Border Width="8" Height="15" >
                <Label Content="*" Padding="0" HorizontalAlignment="Right" Visibility="{Binding ModifiedCueVisibility}" />
            </Border>
            <TextBlock Text="{Binding Path=ModelDisplayName}"/>
        </StackPanel>
    </HierarchicalDataTemplate>
    <HierarchicalDataTemplate x:Key="RootNodeTemplate" 
        ItemsSource="{Binding Path=Children}" >
        <Grid>
            <StackPanel Orientation="Horizontal">
                <TextBlock FontWeight="Bold" Text="{Binding Path=ModelDisplayName}"/>
            </StackPanel>
        </Grid>
    </HierarchicalDataTemplate>
    <local:ManifestNodeTemplateSelector x:Key="manifestNodeTemplateSelector"/>
</Window.Resources>
<Grid>                        
    <TreeView Name="TheManifestTreeView" Grid.Row="0" ItemsSource="{Binding ManifestRoot}" 
              ItemTemplateSelector="{StaticResource manifestNodeTemplateSelector}"
              SelectedItemChanged="TreeView_SelectedItemChanged" >
        <TreeView.ItemContainerStyle>
            <Style TargetType="TreeViewItem">
                <Setter Property="IsExpanded" Value="{Binding IsExpanded}"/>
            </Style>
        </TreeView.ItemContainerStyle>
    </TreeView>
</Grid>

Here is The code for IsExpanded:

    private bool _isExpanded;
    public bool IsExpanded
    {
        get => _isExpanded;
        set
        {
            _isExpanded = value;
            NotifyPropertyChanged("IsExpanded");
        }
    }
2

2 Answers

0
votes

My problem is that I was expecting the tree to automatically expand to a leaf node if that node expanded. If I want the tree to expand to a node, I need to walk up the parentage and expand those.

0
votes

It seems like ItemContainerStyle only applies for first level of TreeViewItem.Try to put the style inside TreeView.Resources instead

<TreeView.Resources>
       <Style TargetType="TreeViewItem">
                <Setter Property="IsExpanded" Value="{Binding IsExpanded}"/>
       </Style>
</TreeView.Resources>