Architect's Log

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

複雑なオブジェクトをバインディングする

アプリ実行


ソースコード

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="HelloWorld.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="150" Width="200">
    <StackPanel>
        <ContentControl Content="{Binding Path=Name.Full}" />
        <TextBlock Text="{Binding Path=Addresses[0].AddressName}" />
        <TextBlock Text="{Binding Path=Addresses[0].Zip}" />
        <TextBlock Text="{Binding Path=Addresses[0].City}" />
    </StackPanel>
</Window>
MainWindow.xaml.cs
using System.Windows;

namespace HelloWorld {
    public partial class MainWindow : Window {
        public MainWindow() {
            InitializeComponent();

            DataContext = new Person(
                new Name(
                    "山田",
                    "太郎"
                ),
                new Address(
                    "会社",
                    "東京都",
                    "160-0006"
                )
            );
        }
    }
}
Person.cs
namespace HelloWorld {
    public class Person {
        public Name Name { get; set; }
        public Address[] Addresses { get; set; }

        public Person(Name name, params Address[] addresses) {
            Name = name;
            Addresses = addresses;
        }
    }
}
Name.cs
namespace HelloWorld {
    public class Name {
        public string First { get; set; }
        public string Last { get; set; }

        public string Full {
            get { return First + " " + Last; }
        }

        public Name(string first, string last) {
            First = first;
            Last = last;
        }
    }
}
Address.cs
namespace HelloWorld {
    public class Address {
        public string AddressName { get; set; }
        public string City { get; set; }
        public string Zip { get; set; }

        public Address(string name, string city, string zip) {
            AddressName = name;
            City = city;
            Zip = zip;
        }
    }
}

参考

FrameworkElement.DataContext プロパティ (System.Windows)
要素がデータ バインドに関与するときの、要素のデータ コンテキストを取得または設定します。