public void CopyXmlToTreeView( XmlNode xNode, ref TreeViewItem tviParent )
{
if (xNode == null)
{
return;
}
if (xNode.HasChildNodes)
{
foreach (XmlNode child in xNode.ChildNodes)
{
TreeViewItem tviChild = new TreeViewItem();
if (child.HasChildNodes)
{
tviChild.Header = child.Name;
tviChild.IsExpanded = true;
tviParent.Items.Add(tviChild);
CopyXmlToTreeView(child, ref tviChild);
}
else if (child.Value != null)
{
tviChild.Header = child.InnerText;
tviParent.Items.Add(tviChild);
}
}
}
}
Thursday, October 18, 2007
Binding a XmlDocument to a TreeView in WPF
So I am working on a project in which I needed to bind a XmlDocument to a TreeView. After hours of staring at the XamlParseError exception (which gives you NO useful information), I finally figured out some of my problems. First off, in order to DataBind the source need to implement IEnumerable. Guess what?? XmlDocument doesn't implement it. So I tried different, to no avail, and I eventually just wrote a (*Gasp*), recursive function to transform a XmlDocument to a TreeView. Didn't think I would ever have to write one of those again! Here it is in all it's glory:
Subscribe to:
Post Comments (Atom)
2 comments:
Hi!
I have used this recursive function and found it very useful but the only problem that I am still having and I hope you have a solution for is that
if there are duplicate nodes in the xmldocument how can you translate the indexing to the treeview.
An example :
(Treeview)
- Root
- Node
- Node
(XmlDocument)
[Root]
[Node/]
[Node/]
[/Root]
if i click the second node how can I tell that I am looking at
Node[2] instead of Node[1].
FYI - replaced with[] since encountering error if using tags
TreeView data binding to xml data file
Post a Comment