Multibind XML到TreeView

时间:2011-03-01 15:48:59

标签: c# wpf xml treeview bind

我有以下xml结构,并希望将其添加到树视图中。下面是我的第一次考试。 我的问题是我不知道如何将列表绑定到树视图,因为childelements必须由poth元素(类别和卡片)组成。

-cards
  -category
    -card
    -card
    -category
      -card
      -card
      -card

<Window.Resources>
    <HierarchicalDataTemplate DataType="cards" ItemsSource="{Binding XPath=card}">
        <TextBlock Text="My Cards" />
    </HierarchicalDataTemplate>

    <HierarchicalDataTemplate DataType="category" ItemsSource="{Binding XPath=card}">
        <TextBlock Text="{Binding XPath=@name}" />
    </HierarchicalDataTemplate>

    <HierarchicalDataTemplate DataType="card" ItemsSource="{Binding XPath=category}">
        <TextBlock Text="{Binding XPath=@name}"/>
    </HierarchicalDataTemplate>

    <XmlDataProvider x:Key="dataxml" XPath="cards" Source="folder\cards.xml" />
</Window.Resources>

<TreeView Name="treeView" ItemsSource="{Binding Source={StaticResource dataxml}, XPath=.}" />

XML示例:

<?xml version="1.0" encoding="utf-8" ?>
<root>
  <settings>
    ....
    ..
  </settings>
  <cards>
    <category name="C1">
        <card name="card1">
            <question>bla</question>
            <answer>blub</answer>
        </card>
        <category name="C2">
            <card name="card4">
                <question>bla</question>
                <answer>blub</answer>
            </card>
        </category>
    </category>
        <card name="card2">
            <question>bla</question>
            <answer>blub</answer>
        </card>
        <card name="card3">
            <question>bla</question>
            <answer>blub</answer>
        </card>
  </cards>
</root>

1 个答案:

答案 0 :(得分:0)

通用方法可以是done like this;对于数据来说,恕我直言是一种很好的方法,如果它确实是任意的。

       <HierarchicalDataTemplate x:Key="NodeTemplate">
            <TextBlock x:Name="tb"/>
            <HierarchicalDataTemplate.ItemsSource>
                <Binding XPath="child::node()" />
            </HierarchicalDataTemplate.ItemsSource>
            <HierarchicalDataTemplate.Triggers>
                <DataTrigger Binding="{Binding Path=NodeType}" Value="Text">
                    <Setter TargetName="tb" Property="Text" Value="{Binding Path=Value}"></Setter>
                </DataTrigger>
                <DataTrigger Binding="{Binding Path=NodeType}" Value="Element">
                    <Setter TargetName="tb" Property="Text" Value="{Binding Path=Name}"></Setter>
                </DataTrigger>
            </HierarchicalDataTemplate.Triggers>
       </HierarchicalDataTemplate>

       <XmlDataProvider x:Key="dataxml" XPath="root" Source="cards.xml"/>

TreeView看起来像这样......

<TreeView HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Name="treeView"
                  ItemTemplate="{StaticResource NodeTemplate}"
                  ItemsSource="{Binding Source={StaticResource dataxml}, XPath=.}" />

如果数据不是任意的,我建议通过LINQ或其他方法解析XML,并将数据移动到复合类型,然后可以通过HierarchicalDataTemplate以更精细的方式绑定到复合类型。如果你走这条路,great walk through应该足以实现你的目标。