You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WinUI3中TreeViewItem.IsExpanded双向绑定仅单向生效问题

解决方案

1. 修正TreeView结构,移除DataTemplate中的TreeViewItem

TreeView会自动为每个数据项生成TreeViewItem容器,无需在ItemTemplate中手动嵌套TreeViewItem。正确的做法是通过ItemContainerStyle绑定容器的IsExpanded和ItemsSource属性,ItemTemplate仅负责定义节点的显示内容。

修改后的XAML代码:

<TreeView x:Name="provenanceTree" 
          Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
          ItemsSource="{x:Bind ProvenanceTreeItems}" 
          SelectionMode="Single">
    <!-- 配置TreeViewItem容器的绑定 -->
    <TreeView.ItemContainerStyle>
        <Style TargetType="TreeViewItem">
            <Setter Property="IsExpanded" Value="{x:Bind isExpanded, Mode=TwoWay}" />
            <Setter Property="ItemsSource" Value="{x:Bind Children}" />
        </Style>
    </TreeView.ItemContainerStyle>
    <!-- 定义节点的显示内容 -->
    <TreeView.ItemTemplate>
        <DataTemplate x:DataType="local:IProvenance">
            <!-- 替换为你原本的节点内容,例如: -->
            <TextBlock Text="{x:Bind YourDisplayProperty}" />
        </DataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

2. 规范依赖属性命名(可选但建议)

按照.NET命名规范,依赖属性和对应CLR属性首字母应大写,避免混淆:

public static DependencyProperty IsExpandedProperty = DependencyProperty.Register(
    nameof(IsExpanded), 
    typeof(bool), 
    typeof(Expandable), 
    new PropertyMetadata(false));

public bool IsExpanded {
    get => (bool)GetValue(IsExpandedProperty);
    set => SetValue(IsExpandedProperty, value);
}

对应XAML中的绑定需同步修改为:

<Setter Property="IsExpanded" Value="{x:Bind IsExpanded, Mode=TwoWay}" />

问题原因分析

你之前在DataTemplate中手动嵌套TreeViewItem,导致TreeView内部的容器机制与手动创建的TreeViewItem产生冲突:

  • UI操作展开/折叠时,手动创建的TreeViewItem能正确同步属性到数据源;
  • 但代码修改数据源属性时,嵌套结构导致绑定的变更通知无法正确传递到TreeView的可视化容器,因此界面无响应。

内容的提问来源于stack exchange,提问作者Jules May

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 20:57:07