我想结合我在XAML定义在其代码隐藏类的属性TreeView控件。 我已经通过阅读WPF基本数据绑定常见问题 ,但在页面的最下方的评论的例子,当我试图用一个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>");
}
}