动态树视图扩展无法与HeirarchicalDataTemplate一起使用

时间:2018-02-14 23:36:02

标签: wpf data-binding treeview

我有一个treeview控件,可以通过模板选择器动态选择项控件。我已经使用Setter将我的模型上的属性IsExpanded绑定到TreeViewItem上的IsExpanded。 (我知道这很复杂,因为如果我在模型构造函数中将IsExpanded设置为true,则会按预期扩展整个树。)

这是问题所在。在我加载树之后,只有根节点是可见的(如预期的那样),但是如果我将节点上的IsExpanded设置为true,那么树应该扩展到更改的节点,但它不会。 (我已将调试标记放入以确保属性实际发生变化。)

这是我的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>

以下是IsExpanded的代码:

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

2 个答案:

答案 0 :(得分:0)

我的问题是,如果该节点扩展,我希望树自动扩展到叶节点。如果我希望树扩展到一个节点,我需要走向父母并扩展它们。

答案 1 :(得分:0)

似乎ItemContainerStyle仅适用于TreeViewItem的第一级。尝试将样式放在TreeView.Resources中

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