我想将我在 XAML 中定义的 TreeView 控件绑定到其代码隐藏类中的属性。我已经阅读了WPF Basic Data Binding FAQ,但是当我尝试使用 XmlDataProvider 作为绑定源时,页面底部注释中的示例不起作用。
如何修改以下代码,以便在 XAML 中而不是在类的构造函数中定义绑定?换句话说,如何修改 TreeView 的ItemsSource
属性以引用其代码隐藏类中的属性?
SomeClass.xaml - 作品
<UserControl x:Class="SomeNamespace.SomeClass"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<UserControl.Resources>
<XmlDataProvider x:Key="SomeTreeData" />
</UserControl.Resources>
<TreeView Name="SomeTree" ItemsSource="{Binding Source={StaticResource SomeTreeData}, XPath=*}">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="items" ItemsSource="{Binding XPath=*}">
<TextBlock Text="{Binding XPath=@Header}" />
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="item" ItemsSource="{Binding XPath=*}">
<TextBlock Text="{Binding XPath=@Header}" />
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
</UserControl>
SomeClass.xaml.cs - 作品
public partial class SomeClass : UserControl
{
public SomeClass()
{
InitializeComponent();
XmlDataProvider lSomeTreeData
= this.FindResource("SomeTreeData") as XmlDataProvider;
lSomeTreeData.Document = new XmlDocument();
lSomeTreeData.Document.LoadXml("<items xmlns=\"\" Header=\"Some items\"><item Header=\"Some item\" /></items>");
}
}
SomeClass.xaml - 所需
注意{SOME MAGIC}
TreeView 的ItemsSource
属性。
<UserControl x:Class="SomeNamespace.SomeClass"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<TreeView Name="SomeTree" ItemsSource="{Binding Source={SOME MAGIC}, XPath=*}">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="items" ItemsSource="{Binding XPath=*}">
<TextBlock Text="{Binding XPath=@Header}" />
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="item" ItemsSource="{Binding XPath=*}">
<TextBlock Text="{Binding XPath=@Header}" />
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
</UserControl>
SomeClass.xaml.cs - 所需
public partial class SomeClass : UserControl
{
public XmlDataProvider SomeXmlDataProvider { get; set; }
public SomeClass()
{
InitializeComponent();
this.SomeXmlDataProvider = new XmlDataProvider();
this.SomeXmlDataProvider.Document = new XmlDocument();
this.SomeXmlDataProvider.Document.LoadXml("<items xmlns=\"\" Header=\"Some items\"><item Header=\"Some item\" /></items>");
}
}