开发者

Easy way to bind XML to Treeview in WPF

I have an XML file that is coded like this:

<?xml version="1.0" encoding="us-ascii"?>
<xml>
<Section ref="01.01" name="Voice Reports">
    <Subsection ref="01.01.01" name="Voice Blocking">
        <Item ref="01.01.01.01" name="CCH Block Count">
            <Description>CCH Block Count</Description>
            <Formula>({#001001_SEIZ_ATTEMPTS_WITH_BUSY_SDCCH})</Formula>
   开发者_如何转开发         <Units>Count</Units>
        </Item>
        <Item ref="01.01.01.02" name="CCH Call Attempts">
            <Description>CCH Call Attempts</Description>
            <Formula>({#001000_SEIZ_ATTEMPTS})</Formula>
            <Units>Count</Units>
        </Item>
    </Subsection>
</Section>
</xml>

What I am trying to do is bind this to a TreeView in WPF so that my top tree node will say "01.01 Voice Reports" and under that "01.01.01 Voice Blocking" and under that have each Item as a tree item.

What is the easiest way to do this using WPF 4 and C#?


One way to do this is to read the XML and convert into objects before doing databinding with HierarchicalDataTemplates.

Note that in the code below I don't do much error checking. I copied your XML directly into XMLFile1.xml.

MainWindow.xaml.cs:

using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Xml.Linq;

namespace WpfApplication
{
    public class Attributes
    {
        public string Ref { get; set; }
        public string Name { get; set; }
        public override string ToString()
        {
            return Ref + " " + Name;
        }
    }

    public class Section
    {
        public Attributes Attributes { get; set; }
        public List<SubSection> SubSections { get; set; }
    }

    public class SubSection
    {
        public Attributes Attributes { get; set; }
        public List<Item> Items { get; set; }
    }

    public class Item
    {
        public Attributes Attributes { get; set; }
        public string Description { get; set; }
        public string Units { get; set; }
        public string Formula { get; set; }

    }

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            LoadFile();
            DataContext = this;
        }

        public List<Section> Sections
        {
            get;
            private set;
        }

        private void LoadFile()
        {
            XDocument xmlFile = XDocument.Load(@"XMLFile1.xml");

            var q = from section in xmlFile.Descendants("Section")
                    select new Section()
                    {
                        Attributes = new Attributes() 
                        {
                            Ref = section.Attribute("ref").Value,
                            Name = section.Attribute("name").Value 
                        },
                        SubSections = new List<SubSection>(from subsection in section.Descendants("Subsection")
                                      select new SubSection()
                                      {
                                          Attributes = new Attributes()
                                          {
                                              Ref = subsection.Attribute("ref").Value,
                                              Name = subsection.Attribute("name").Value
                                          },
                                          Items = new List<Item>(from item in subsection.Descendants("Item")
                                                   select new Item()
                                                   {
                                                       Attributes = new Attributes()
                                                       {
                                                           Ref = item.Attribute("ref").Value,
                                                           Name = item.Attribute("name").Value
                                                       },
                                                       Description = item.Element("Description").Value,
                                                       Formula = item.Element("Formula").Value,
                                                       Units = item.Element("Units").Value
                                                   })
                                      })
                    };

            Sections = new List<Section>(q);
        }
    }
}

The in the XAML file (MainWindow.xaml):

<Window x:Class="WpfApplication.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:src="clr-namespace:WpfApplication"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.Resources>
            <HierarchicalDataTemplate DataType = "{x:Type src:Section}"
                                ItemsSource = "{Binding Path=SubSections}">
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Path=Attributes}"/>
                </StackPanel>
            </HierarchicalDataTemplate>
            <HierarchicalDataTemplate DataType = "{x:Type src:SubSection}"
                                ItemsSource = "{Binding Path=Items}">
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Path=Attributes}"/>
                </StackPanel>
            </HierarchicalDataTemplate>
            <DataTemplate DataType = "{x:Type src:Item}">
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Path=Attributes}"/>
                    <TextBlock Text="    " />
                    <TextBlock Text="{Binding Path=Description}" />
                    <TextBlock Text=" " />
                    <TextBlock Text="{Binding Path=Formula}" />
                    <TextBlock Text=" " />
                    <TextBlock Text="{Binding Path=Units}" />
                </StackPanel>
            </DataTemplate>
        </Grid.Resources>

        <TreeView ItemsSource="{Binding Sections}" />
    </Grid>
</Window>

You should see something like this:

Easy way to bind XML to Treeview in WPF

You can find out more about hierarchical data templates on MSDN.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜