views:

305

answers:

1

How can I recursivly bind a Treeview to an XDocument, mapping each XML Element to a Node in the Treeview?

The code below should work from my perspective (and also according to the very few posts I found regarding direct binding), however it does not:

<sdk:TreeView ItemsSource="{Binding Path=Elements}" DataContext="{Binding Path=Data}">
  <sdk:TreeView.ItemTemplate>
   <data:HierarchicalDataTemplate ItemsSource="{Binding Path=Elements}">
    <StackPanel Orientation="Vertical">
     <TextBlock Text="{Binding Name}"/>
    </StackPanel>
   </data:HierarchicalDataTemplate>
  </sdk:TreeView.ItemTemplate>
</sdk:Treeview>

(Data is a Property of type XElement on the parents' DataContext)

Did I make a mistake somewhere or do I really need to implement an IValueConverter just to get at the child elements of an XElement?

A: 

The "Elements" member is not a Property, It's a Method call.
You cannot bind to method calls in Silverlight.

If you're really bent on getting this scenario to work you've got 2 options I can see:
1. Use an IValueConverter to extract the contents of the "Elements" method.
2. Wrap the XDocument in managed classes in a proper hierarchy.

Personally, While option #1 seems the fastest, I believe that in the long run it'll cost you more time to maintain and support then spending an additional 10 minutes building a proper domain model.

Sincerely,
-- Justin Angel

JustinAngel
Justin, thanks for your insights. I'm creating a simple XML Editor for varying input Schemes, so the XDocument IS my domain model - I can't see the advantage of creating/generating a code replica of each of my XML Schemas versus "keeping the editor unaware".[Edit] Altough I might give Linq2Xsd a try...
Michael Wagner
Michael, You don't need any fancy tools. Just build a simple 3 properties wrapper around LinqToXml classes with Name, Value and Children. That's about 10 lines worth of code, and then databind to that. Let me know if you're having problems implementing that approach.
JustinAngel
A bit late, but for completeness: I ended up doing exactly that, wrote myself a (not so thin) wrapper and also put in some convenience methods and properties. Thanks!
Michael Wagner