WPF TreeView 仅展开根

WPF TreeView expand roots only

默认情况下应该展开 TreeView 中的所有根项目。根项具有与子项不同的 ViewModel。

树视图 XAML:

<TreeView>
    <TreeView.Resources>
        <HierarchicalDataTemplate DataType="{x:Type models:RootModel}" ItemsSource="{Binding Roots}">
            <TextBlock Text="{Binding Title}"/>
        </HierarchicalDataTemplate>
        <HierarchicalDataTemplate DataType="{x:Type models:Child1Model}" ItemsSource="{Binding Childs}">
            <TextBlock Text="{Binding Title}"/>
        </HierarchicalDataTemplate>
        <DataTemplate DataType="{x:Type models:Child2Model}">
            <TextBlock Text="{Binding Title}"/>
        </DataTemplate>
    </TreeView.Resources>
</TreeView>

层次结构是这样的:

应展开具有根视图模型的所有项目,同时折叠所有子项目。我如何实现这种行为?我对 WPF 还是很陌生,所以我真的不知道该怎么做,但我尝试了一些 'research':

之后的事情

在视图模型中定义一个IsExpanded属性:显然不会用到

private bool _isExpanded = true;
public bool IsExpanded
{
    get => _isExpanded;
    set
    {
        _isExpanded = value;
        OnPropertyChanged(nameof(IsExpanded)); //base.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

将样式应用于 HierachicalDataTemplate:它不支持 TreeViewItem 本身的样式,仅支持容器。

<Style x:Key="RootItem" TargetType="TreeViewItem">
    <Style.Setters>
        <Setter Property="IsExpanded" Value="True"/>
    </Style.Setters>
</Style>
<HierarchicalDataTemplate DataType="{x:Type models:RootModel}" ItemsSource="{Binding Roots}" ItemContainerStyle="{StaticResource RootItem}">

我找到了如何设置展开全部 TreeViewItems 的答案,但我无法将其修改为仅影响一个 itemtype/viewmodel。

<TreeView>
    <TreeView.ItemContainerStyle>
        <Style TargetType="{x:Type TreeViewItem}">
            <Setter Property="IsExpanded" Value="True" />
        </Style>
    </TreeView.ItemContainerStyle>
</TreeView>

非常感谢任何帮助。提前致谢。

我必须通过上述答案将 TreeViewItem 属性 IsExpanded 绑定到我的视图模型。 在我的视图模型中,我定义了 属性 IsExpanded:

private bool _isExpanded = true;
public bool IsExpanded
{
    get => _isExpanded;
    set
    {
        _isExpanded = value;
        OnPropertyChanged(nameof(IsExpanded)); //base.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

然后双向绑定到 TreeViewItem 属性:

<TreeView.ItemContainerStyle>
    <Style TargetType="{x:Type TreeViewItem}">
    <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
    <Setter Property="FontWeight" Value="Normal" />
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="FontWeight" Value="Bold" />
        </Trigger>
    </Style.Triggers>
</Style>
</TreeView.ItemContainerStyle>

仍然;连线它不适用于我尝试过的样式,因为这实际上是相同的。