c# - 如何将 Xml 属性绑定(bind)到 Treeview 节点,同时将 XDocument 数据绑定(bind)到 WPF Treeview

标签 c# wpf data-binding xaml treeview

我有一个 XML 需要数据绑定(bind)到 WPF TreeView。这里的 XML 可以有不同的结构。 TreeView 应该是数据绑定(bind)通用的,足以加载层次结构的任何排列。然而,节点上的 XAttribute(称为 Title)应该数据绑定(bind)到 TreeViewItem 的header text不是节点名 .

要绑定(bind)的XML:

<Wizard>
  <Section Title="Home">
    <Loop Title="Income Loop">
      <Page Title="Employer Income"/>
      <Page Title="Parttime Job Income"/>
      <Page Title="Self employment Income"/>
    </Loop>
  </Section>
  <Section Title="Deductions">
    <Loop Title="Deductions Loop">
      <Page Title="Travel spending"/>
      <Page Title="Charity spending"/>
      <Page Title="Dependents"/>
    </Loop>
  </Section>
</Wizard>

XAML:

<Window x:Class="Wpf.DataBinding.TreeViewer"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Wpf.DataBinding"
    Title="TreeViewer" Height="300" Width="300">
    <Window.Resources>
        <HierarchicalDataTemplate ItemsSource="{Binding Path=Elements}" x:Key="TVTemplate">
            <TreeViewItem Header="{Binding Path=Name}"/>
        </HierarchicalDataTemplate>
    </Window.Resources>
    <StackPanel>
        <TreeView x:Name="_treeView" Style="{StaticResource TVallExpanded}"
                ItemsSource="{Binding Path=Root.Elements}"
                ItemTemplate="{StaticResource TVTemplate}" />
    </StackPanel>
</Window>

将 XML 加载到 XDocument 并将其绑定(bind)到 TreeView 的 XAML 代码隐藏

public partial class TreeViewer : Window
{
    public TreeViewer()
    {
        InitializeComponent();
        XDocument doc = XDocument.Parse(File.ReadAllText(@"C:\MyWizard.xml"));
        _treeView.DataContext = doc;
    }
}

所以在 XAML 标记中,我们将 Name 绑定(bind)到 TreeViewItem 的 header 。

<TreeViewItem Header="{Binding Path=Name}"/>

但是,我想将它绑定(bind)到上面Xml 中Section、Loop 和Page 的Title 属性。我读到在绑定(bind) XDocument 时不可能使用 XPath。但是必须有一种方法可以将 Title 属性绑定(bind)到 TreeViewItem 的标题文本。我尝试使用 @Title、.[@Title] 等。但似乎都不起作用。

thread on MSDN Forums有类似的讨论。

任何指针都会非常有帮助。

最佳答案

欢呼!!!我想出了如何绑定(bind) XAttribute。它不直观,也不容易想象。但这是如何做到的。

<TreeViewItem Header="{Binding Path=Attribute[Title].Value}"/>

很难想象Title可以直接用在方括号中

More @ this MSDN link

关于c# - 如何将 Xml 属性绑定(bind)到 Treeview 节点,同时将 XDocument 数据绑定(bind)到 WPF Treeview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/238196/

相关文章:

c# - 可以使用相同的列表,但仍然是空的

c# - 尝试禁用在 WPF 应用程序中出现 i 'flick' 时出现的手势工具提示

wpf - Qt QML 组件,如 WPF HwndHost

c# - 如何在 wpf datagrid 中绑定(bind)行标题?

data-binding - 双向 JavaFX 绑定(bind)被不相关的代码破坏

c# - 什么允许匿名无参数委托(delegate)类型有所不同?

c# - 使用正则表达式 (.NET) 查找 unicode 数字

c# - 如何从 wpf 文本框中的十进制数字中删除无效条目

wpf - 如何正确绑定(bind)到 MVVM 框架中用户控件的依赖属性

c# - 绑定(bind)工作正常,但智能感知显示 : Cannot resolve property XXX in data context of type 'object'