XAML で定義した TreeView コントロールを分離コード クラスのプロパティにバインドしたいと考えています。私はすでにWPF Basic Data Binding FAQを読みましたが、バインディング ソースとして XmlDataProvider を使用しようとしたときに、ページの一番下にあるコメントの例が機能しませんでした。
バインディングがクラスのコンストラクターではなく XAML で定義されるように、次のコードを変更するにはどうすればよいですか? ItemsSource
つまり、コード ビハインド クラスのプロパティを参照するように TreeView の属性を変更するにはどうすればよいでしょうか。
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>");
}
}