如何将XmlDataProvider类属性绑定到XAML TreeView

我想将我在XAML中定义的TreeView控件绑定到其代码隐藏类中的属性。 我已经阅读了WPF基本数据绑定常见问题解答 ,但是当我尝试使用XmlDataProvider作为绑定源时,页面底部注释中的示例不起作用。

如何修改以下代码,以便在XAML中定义绑定,而不是在类的构造函数中定义? 换句话说,如何修改TreeView的ItemsSource属性以引用其代码隐藏类中的属性?

SomeClass.xaml – Works

                

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(""); } } 

SomeClass.xaml – 期望

请注意TreeView的ItemsSource属性中的{SOME MAGIC}

             

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(""); } } 

我发现一个选项是设置控件的DataContext

             

 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(""); this.DataContext = this.SomeXmlDataProvider.Document; } }