Architect's Log

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

XMLを動的にバインドする

データソースを動的に判断する必要がある場合は、DataContextプロパティを使用します。

アプリ実行


ソースコード

App.xaml
<Application x:Class="HelloWorld.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="HelloWorld2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="100" Width="200"
        DataContext="{DynamicResource dataSource}">
    <Window.Resources>
        <XmlDataProvider x:Key="dataSource">
            <x:XData>
                <Media xmlns="">
                    <Book Author="山田" Title="愛は天国" />
                    <Book Author="鈴木" Title="愛は地獄" />
                    <Book Author="佐藤" Title="愛は生きる糧" />
                    <CD Author="佐藤" Title="愛子は歌う" />
                    <DVD Director="山田" Title="愛という名の映画">
                        <Actor>佐藤</Actor>
                        <Actor>鈴木</Actor>
                    </DVD>
                </Media>
            </x:XData>
        </XmlDataProvider>
    </Window.Resources>
    <ListBox ItemsSource="{Binding XPath=/Media/Book/@Title}" />
</Window>