c# - 在 WPF 中将 XML 绑定(bind)到 Treeview 的简单方法

标签 c# wpf xml treeview

我有一个编码如下的 XML 文件:

<?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>

我想做的是将其绑定(bind)到 WPF 中的 TreeView,以便我的顶部树节点将显示“01.01 语音报告”,在该“01.01.01 语音阻止”下,将每个项目作为树项目.

使用 WPF 4 和 C# 执行此操作的最简单方法是什么?

最佳答案

执行此操作的一种方法是在使用 HierarchicalDataTemplates 进行数据绑定(bind)之前读取 XML 并将其转换为对象。

请注意,在下面的代码中,我没有做太多错误检查。我将您的 XML 直接复制到 XMLFile1.xml 中。

主窗口.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);
        }
    }
}

XAML 文件 (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>

你应该看到这样的东西: MainWindow

您可以在 MSDN 上找到有关分层数据模板的更多信息.

关于c# - 在 WPF 中将 XML 绑定(bind)到 Treeview 的简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4120449/

相关文章:

c# - 当轮廓可以撕裂时,如何检测简单形状(使用emgu cv)?

c# - 注入(inject)和 WebAPI : Getting started after install from NuGet

c# - 在 TreeViewItem WPF 中设置 SelectionActive

c# - XmlReader - 读取没有换行符的 xml 文件时出现问题

c# - OWIN 干扰 log4net

c# - Messagebox 多次显示

c# - MSHTML COM 单击提交按钮时出现问题

xml - 如何在 XSLT 中正确分支?

php - 通过php将xml数据插入mysql数据库

javascript - 如何在 php 语言(或 javascript)上将 InDesign 文件与 XML 标签文件粘合?