gpt4 book ai didi

c# - WPF:绑定(bind) TreeView

转载 作者:太空宇宙 更新时间:2023-11-03 16:49:47 24 4
gpt4 key购买 nike

我有一个数据源:

private List<PlayData> _treeData = new List<PlayData>();

private void Test()
{
_treeData.Add(new PlayData()
{
BoolList = new List<bool>() { true, false, true },
Name = "A"
});

_treeData.Add(new PlayData()
{
BoolList = new List<bool>() { true, false, true },
Name = "B"
});

DataContext = this;
}

我如何在 XAML 中绑定(bind)它,以便 Name 是父项而 Bool 的列表是子项。我试过这个失败了:

    <TreeView x:Name="treeView" Height="200" ItemsSource="{Binding Path=TreeData}" >
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=BoolList, Mode=TwoWay}" >
<TextBlock FontWeight="Bold" Text="{Binding Path=Name, Mode=TwoWay}" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>

最佳答案

从您的示例中不清楚您在做什么 - 但本质上

  1. 您必须在名为 TreeData 的代码中定义一个公共(public)属性(示例中缺少,但假设这是返回 _treeData 的属性)
  2. BoolList 需要是 TreeData 的子属性(似乎是这样)
  3. 您需要为 TreeView 中包含子元素的每个元素定义一个 HierarchicalTemplate。
  4. 为 TreeView 中不包含子元素的每个元素定义一个常规的DataTemplate

如果像您的情况一样有不同的数据类型,您需要声明对象的类型

 <HierarchicalDataTemplate DataType="{x:Type foo:PlayData}"
ItemsSource="{Binding BoolList}">

如果可以有多个匹配项,模板的顺序很重要。

关于c# - WPF:绑定(bind) TreeView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4386792/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com