c# - WPF - Good Way to take a list to a Tree -
i have list looks this:
base/level1/item1 base/level1/item2 base/level1/sub1/item1 base/level2/item1 base/level3/sub1/item1
i easy way put listview. (ie similar this)
base | +->level1 | | | +=item1 | +=item2 | | | +->sub1 | | | +=item1 | +->level2 | | | +=item1 | +->level3 | +->sub1 | +=item1
is there established way make kind of conversion or need roll own parser?
(in case may relevant real items in code tfs iteration paths.)
this take list of strings , turn tree suitable viewing treeview described:
public ilist buildtree(ienumerable<string> strings) { return s in strings let split = s.split("/") group s s.split("/")[0] g // group first component (before /) select new { name = g.key, children = buildtree( // recursively build children s in grp s.length > g.key.length+1 select s.substring(g.key.length+1)) // select remaining components }; }
this return tree of anonymous types, each containing name property , children property. can bound directly treeview
specifying hierarchicaldatatemplate
itemssource="{binding children}"
, content consisting of <textblock text="{binding name}">
or similar.
alternatively define tree node class in code if want additional members or semantics. example, given node class:
public class node { public string name { get; set; } public list<node> children { get; set; } }
your buildtree function different:
public list<node> buildtree(ienumerable<string> strings) { return ( s in strings let split = s.split("/") group s s.split("/")[0] g // group first component (before /) select new node { value = g.key, children = buildtree( // recursively build children s in grp s.length > g.key.length+1 select s.substring(g.key.length+1)) // select remaining components } ).tolist(); }
again can bound directly using hierarchicaldatatemplate
. use first solution (anonymous types) unless want special tree nodes.
Comments
Post a Comment