我有一个 XML,需要将数据绑定到WPF 树视图。这里 XML 可以有不同的结构。 TreeView 应该是数据绑定通用的,足以加载层次结构的任何排列。然而X属性在节点上(称为Title)应该数据绑定到 TreeViewItem 的标题文本 and 不是节点名.
待绑定的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 并将其绑定到 TreeView 的 XAML 代码隐藏
public partial class TreeViewer : Window
{
public TreeViewer()
{
InitializeComponent();
XDocument doc = XDocument.Parse(File.ReadAllText(@"C:\MyWizard.xml"));
_treeView.DataContext = doc;
}
}
因此,在 XAML 标记中,我们将 Name 绑定到 TreeViewItem 的标头。
<TreeViewItem Header="{Binding Path=Name}"/>
但是,我想将它绑定到Title上面Xml中Section、Loop和Page的属性。我读到绑定 XDocument 时不可能使用 XPath。但必须有一种方法来绑定TitleTreeViewItem 的标题文本的属性。我尝试使用@Title、.[@Title]等,但似乎都不起作用。
This MSDN 论坛上的主题 http://social.msdn.microsoft.com/forums/en-US/wpf/thread/edd843b7-b378-4c2d-926f-c053dbd7b340有类似的讨论。
任何指示都会非常有帮助。