Architect's Log

I'm a Cloud Architect. I'm highly motivated to reduce toils with driving DevOps.

DataTemplateを使用してXMLをバインディングする

アプリ実行


ソースコード

App.xaml
<Application x:Class="WpfApplication6.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
</Application>
MainWindow.xaml
<Window x:Class="WpfApplication6.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sx="clr-namespace:System.Xml;assembly=System.Xml"
        DataContext="{DynamicResource dataSource}"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <XmlDataProvider x:Key="dataSource">
            <x:XData>
                <Company xmlns="">
                    <Section Manager="山田太郎" SectionName="総務部" />
                    <Section Manager="山田太郎" SectionName="経理部" />
                    <Section Manager="渡辺次郎" SectionName="人事部" />
                </Company>
            </x:XData>
        </XmlDataProvider>
        <DataTemplate x:Key="template" DataType="{x:Type sx:XmlElement}">
            <TextBlock Text="{Binding XPath=@SectionName}" />
        </DataTemplate>
    </Window.Resources>
    <ListBox
        ItemsSource="{Binding XPath=/Company/Section}"
        ItemTemplate="{DynamicResource template}" />
</Window>