WinUI3中如何将ViewModel属性绑定到TreeViewItem.IsSelected
问题根因
WinUI3的TreeView会自动为每个数据项生成TreeViewItem作为容器,你在DataTemplate中定义的TreeViewItem会被嵌套在自动生成的容器内部,你绑定的是内层TreeViewItem的属性,对实际生效的外层容器没有作用,所以绑定失效。
解决方案
修改XAML中TreeView的配置,通过ItemContainerStyle绑定实际容器的属性即可,具体修改如下:
1. 修正MainWindow.xaml代码
<Window x:Class="WinUITreeViewTest.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:WinUITreeViewTest" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> <!-- 移除StackPanel上错误的DataContext字符串赋值 --> <StackPanel> <TreeView Name="MyItemView" SelectionMode="Multiple" ItemsSource="{Binding MyItems}"> <!-- 用ItemContainerStyle绑定TreeView自动生成的容器属性 --> <TreeView.ItemContainerStyle> <Style TargetType="TreeViewItem"> <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/> <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}"/> <Setter Property="ItemsSource" Value="{Binding Children}"/> </Style> </TreeView.ItemContainerStyle> <!-- ItemTemplate只定义节点的内容展示,不需要再嵌套TreeViewItem --> <TreeView.ItemTemplate> <DataTemplate x:DataType="local:MyItem"> <TextBlock Text="{Binding Name}"/> </DataTemplate> </TreeView.ItemTemplate> </TreeView> </StackPanel> </Window>
2. 功能验证
修改后无需改动其他C#代码:
- 启动时ViewModel中
IsSelected=true的节点会自动被选中,满足初始化选中需求 - 用户手动勾选/取消勾选节点时,ViewModel中对应
MyItem的IsSelected属性会自动同步更新,可直接读取状态
内容的提问来源于stack exchange,提问作者Katsutoshi Hayashida
相关产品推荐
相关产品推荐

