【问题标题】:WPF: Binding TreeViewWPF:绑定树视图
【发布时间】:2010-12-08 11:11:58
【问题描述】:

我有一个数据源:

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 中绑定它,以便 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> 

【问题讨论】:

  • “不成功”是什么意思?

标签: c# .net wpf vb.net xaml


【解决方案1】:

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

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

如果你的情况有不同的数据类型,你需要声明对象的类型

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

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

【讨论】:

    【解决方案2】:

    _treeData 字段需要作为属性公开才能被绑定。从您的示例代码中不清楚您是否这样做。

    您还可以在两个 Binding 上去掉 Mode=TwoWay,因为没有输入可以推回源值。

    【讨论】:

      猜你喜欢
      • 2012-02-20
      • 1970-01-01
      • 2015-07-10
      • 2011-07-14
      • 2011-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多