Sunday, April 17, 2011

Binding XML data to WPF treeview Control

I have spend a lot of time trying to figure out how to bind data in my XML file to the TreeView control but I do not know where to start. I even tried going through http://stackoverflow.com/questions/188001/two-way-binding-of-xml-data-to-the-wpf-treeview and Josh Smith's code sample on codeproject, but still can't understand how to begin!!!

I have XML in in a file "C:\SPDependencies.xml" (I can change the format if required)!!!:

  <node type="SPDependencies" Name="SPDependencies">
        <node type="StoredProc" Name="SP1">
                <node type="OperationType" Name="Type1">
                        <node type="TableName" Name="Table1"/>
                        <node type="TableName" Name="Table2"/>
                </node>
                <node type="OperationType" Name="Type2">
                         <node type="TableName" Name="Table1"/>
                        <node type="TableName" Name="Table2"/>
                </node>
                 .....
        </node>
        <node type="StoredProc" Name="SP2">
              <node type="OperationType" Name="Type1">
              ...
              ...
        </node>
</node>

I need to display this in the Treeview control in the following format:

<SP1>
   <Type1>
      <Table1>
      <Table2>
      <Table3>
   <Type2>
      <Table1>
      <Table2>
      <Table3>
<SP2>
    <Type1>
........

Thanks, Abhi.

From stackoverflow
  • Heres the tree:

    <Window.Resources>
        <HierarchicalDataTemplate DataType="node"
                                  ItemsSource="{Binding XPath=node}">
            <TextBox Width="Auto"
                     Text="{Binding XPath=@Name, UpdateSourceTrigger=PropertyChanged}" />
        </HierarchicalDataTemplate>
    
        <XmlDataProvider
            x:Key="xmlDataProvider"
            XPath="node" Source="C:\Data.XML">
        </XmlDataProvider>
    </Window.Resources>
    <Grid>
        <StackPanel>
            <Button Click="Button_Click">Save</Button>
                <TreeView
                    Width="Auto"
                    Height="Auto"
                    Name="treeview"
                    ItemsSource="{Binding Source={StaticResource xmlDataProvider}, XPath=.}"/>
         </StackPanel>
    </Grid>
    

    I've added a simple button to save changes. So for your Button_Click method in code behind:

    XmlDataProvider dataProvider = this.FindResource("xmlDataProvider") as XmlDataProvider;
    dataProvider.Document.Save(dataProvider.Source.LocalPath);
    

    See here for an article about data binding and WPF.

    Number8 : I'm interested in this topic, as well. Is there something missing in your answer? I can't get any data to display... Thanks.
    Crippeoblade : I suggest you create a new question and post your code so we can see what the problem is.

0 comments:

Post a Comment