我有一个数据源:
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>
最佳答案
从您的示例中不清楚您在做什么 - 但本质上
- 您必须在名为
TreeData
的代码中定义一个公共(public)属性(示例中缺少,但假设这是返回 _treeData
的属性) BoolList
需要是TreeData
的子属性(似乎是这样)- 您需要为 TreeView 中包含子元素的每个元素定义一个 HierarchicalTemplate。
- 为 TreeView 中不包含子元素的每个元素定义一个常规的
DataTemplate
如果像您的情况一样有不同的数据类型,您需要声明对象的类型
<HierarchicalDataTemplate DataType="{x:Type foo:PlayData}"
ItemsSource="{Binding BoolList}">
如果可以有多个匹配项,模板的顺序很重要。
关于c# - WPF:绑定(bind) TreeView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4386792/