3

我需要用我拥有的字典列表填写 TreeView。

List<Dictionary<string,object>> 

字典有标题和子键的地方

[{"title":"foo", "children":[]},]

但是我无法弄清楚绑定。这是完全错误的。我显然需要显示 dict["title"] 并使用 dict["children"] 作为孩子。

<TreeView.ItemTemplate>
    <HierarchicalDataTemplate ItemsSource="{Binding Value}">
       <HierarchicalDataTemplate.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding}"/>
            </DataTemplate>
        </HierarchicalDataTemplate.ItemTemplate>
        <TextBlock Text="{Binding Key}"/>
    </HierarchicalDataTemplate>
</TreeView.ItemTemplate>

哈哈,显然 Binding 支持 [] 语法,所以这种工作:

        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate ItemsSource="{Binding Path=[children]}">
                <HierarchicalDataTemplate.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Path=[title]}"/>
                    </DataTemplate>
                </HierarchicalDataTemplate.ItemTemplate>
                <TextBlock Text="{Binding Path=[title]}"/>
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>

但是,每个字典都可以将子级嵌套到他们想要的任意多个级别。这可以处理吗?使用上面的模板和下面的代码,孙子不显示。

        string s = @"[{""title"":""Title1"",""children"":[{""title"":""Child1"",""children"":[{""title"":""grandchild1"",""children"":[]}]}]}]";

        List<Dictionary<string, object>> marr = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(s);
        mTreeView.ItemsSource = marr;

顺便说一下,在 Binding 中使用 [] 称为索引器,我从这个链接的文档中找到了它:

http://msdn.microsoft.com/en-us/library/ms752300.aspx#Path_Syntax

4

1 回答 1

1

这是你正在看的东西:

<TreeView ItemsSource="{Binding ElementName=rootWindow, Path=Directories}">
        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate ItemsSource="{Binding [Children]}">
                <TextBlock Text="{Binding [Title]}" />
                <HierarchicalDataTemplate.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding}" />
                    </DataTemplate>
                </HierarchicalDataTemplate.ItemTemplate>
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>

这就是我填充数据的方式:

Dictionary<string, object> documentsDictionary = new Dictionary<string, object>();
        List<string> documentsDictionaryChildren = new List<string> { "Document1", "Document2", "Document3", "Document4", "Document5" };
        documentsDictionary.Add("Title", "Documents");
        documentsDictionary.Add("Children", documentsDictionaryChildren);

        Dictionary<string, object> picturesDictionary = new Dictionary<string, object>();
        List<string> picturesDictionaryChildren = new List<string> { "Picture1", "Picture2", "Picture3", "Picture4", "Picture5" };
        picturesDictionary.Add("Title", "Pictures");
        picturesDictionary.Add("Children", picturesDictionaryChildren);

        Directories.Add(documentsDictionary);
        Directories.Add(picturesDictionary);
于 2013-04-04T09:57:38.547 回答