UWP・WPFメモ　データバインディング

# <i class="fa fa-cubes" style="font-size:1em;"></i> UWP

## <i class="fa fa-cube" style="font-size:1em;"></i> UWPサンプル1
![u01.png](https://qiita-image-store.s3.amazonaws.com/0/142879/54b25e3b-ffae-2768-2303-094eac45ff45.png)

```Xml:MainPage.xaml
<Page
    x:Class="UwpApp1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:UwpApp1"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Slider x:Name="slider" Value="30" Maximum="100" Margin="0,15,0,0"/>
        <ProgressBar Height="10" Value="{Binding ElementName=slider,Path=Value}" Maximum="100" Margin="0,15,0,0"/>
        <TextBox Text="{Binding ElementName=slider,Path=Value,Mode=TwoWay}" Margin="0,15,0,0"/>
    </StackPanel>
</Page>
```

## <i class="fa fa-cube" style="font-size:1em;"></i> UWPサンプル2（コレクション）
![u02.png](https://qiita-image-store.s3.amazonaws.com/0/142879/e0de738a-2d41-e3b2-6073-7962f9c272f3.png)

```Xml:MainPage.xaml
<Page
    x:Class="UwpApp2.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:UwpApp2"
    xmlns:vm="using:UwpApp2.ViewModels"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    <Page.DataContext>
        <vm:PersonVM />
    </Page.DataContext>

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>

        <!-- 左側：そのまま表示 -->
        <ListBox Grid.Column="0" ItemsSource="{Binding Path=Persons}" DisplayMemberPath="Name" />

        <!-- 右側：表示をカスタマイズ -->
        <ListBox Grid.Column="1" ItemsSource="{Binding Path=Persons}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Text="{Binding Name}" FontWeight="Bold"/>
                        <TextBlock Text="{Binding Memo}"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Page>
```

```CSharp:PersonVM.cs
using System.Collections.Generic;
using UwpApp2.Models;

namespace UwpApp2.ViewModels
{
    public class PersonVM
    {
        // リスト内容の変更に対応する場合は
        // List の代わりに System.Collections.ObjectModel.ObservableCollection を使う
        public List<Person> Persons { get; set; }

        public PersonVM()
        {
            this.Persons = new List<Person>();

            this.Persons.Add(new Person { Name = "太郎", Age = 10, Memo = "あいうえお" });
            this.Persons.Add(new Person { Name = "次郎", Age = 8, Memo = "aaa" });
            this.Persons.Add(new Person { Name = "三郎", Age = 3, Memo = "123456" });
        }
    }
}
```

```CSharp:Person.cs
namespace UwpApp2.Models
{
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Memo { get; set; }
    }
}
```

## <i class="fa fa-cube" style="font-size:1em;"></i> UWPサンプル3（コンバーター）
![u03.png](https://qiita-image-store.s3.amazonaws.com/0/142879/6efb13a9-6a5a-c883-9ed4-5a4eac36228c.png)

```Xml:MainPage.xaml
<Page
    x:Class="UwpApp3.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:UwpApp3"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    <Page.Resources>
        <local:BooleanToMessageConverter x:Key="BoolToMsgConv"/>
    </Page.Resources>
    
    <StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <CheckBox x:Name="checkbox" Content="表示" IsChecked="True" Margin="0,15,0,0"/>

        <!-- Windows 10、バージョン1607以降はXAMLフレームワークにbool値とVisibility値のコンバーターが組み込まれている -->
        <Button Content="ボタン" Visibility="{Binding ElementName=checkbox,Path=IsChecked}" Margin="0,15,0,0"/>
        
        <TextBlock Text="{Binding ElementName=checkbox,Path=IsChecked,Converter={StaticResource BoolToMsgConv}}" Margin="0,15,0,0"/>
    </StackPanel>
</Page>
```

```CSharp:BooleanToMessageConverter.cs
using System;

namespace UwpApp3
{
    /// <summary>
    /// 真偽値からメッセージへ変換
    /// </summary>
    public class BooleanToMessageConverter : Windows.UI.Xaml.Data.IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if (value is bool && (bool)value)
            {
                return "Trueです。";
            }
            else
            {
                return "Falseです。";
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }
}
```

## <i class="fa fa-cube" style="font-size:1em;"></i> UWPサンプル4（コンパイル時バインディング）
![u04.png](https://qiita-image-store.s3.amazonaws.com/0/142879/c0ff7164-3788-cdf6-0311-d1350f31d332.png)

```Xml:MainPage.xaml
<Page
    x:Class="UwpApp4.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:UwpApp4"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    <StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock Text="{x:Bind Message1,Mode=TwoWay}" Margin="0,15,0,0" />
        <Button Content="ボタン" Click="{x:Bind Button_Click}" Margin="0,15,0,0" />
    </StackPanel>
</Page>
```

```CSharp:MainPage.xaml.cs
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

// 空白ページのアイテム テンプレートについては、http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 を参照してください

namespace UwpApp4
{
    /// <summary>
    /// それ自体で使用できる空白ページまたはフレーム内に移動できる空白ページ。
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public static readonly DependencyProperty Message1Property = 
            DependencyProperty.Register(
              "Message1",
              typeof(string),
              typeof(MainPage),
              new PropertyMetadata(null)
            );
        public string Message1
        {
            get { return (string)GetValue(Message1Property); }
            set { SetValue(Message1Property, (string)value); }
        }

        public MainPage()
        {
            this.InitializeComponent();
            this.Message1 = "こんにちは";
        }

        public void Button_Click(object sender, RoutedEventArgs e)
        {
            this.Message1 = "さようなら";
        }
    }
}
```

# <i class="fa fa-cubes" style="font-size:1em;"></i> WPF

## <i class="fa fa-cube" style="font-size:1em;"></i> WPFサンプル1
![w01.png](https://qiita-image-store.s3.amazonaws.com/0/142879/e28b47cd-2af3-6f85-f51b-97fc5fd28de2.png)

```Xml:MainWindow.xaml
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <Slider x:Name="slider" Value="30" Interval="1" IsSnapToTickEnabled="True" Maximum="100" Margin="0,15,0,0"/>
        <ProgressBar Height="10" Value="{Binding ElementName=slider,Path=Value}" Maximum="100" Margin="0,15,0,0"/>
        <TextBox Text="{Binding ElementName=slider,Path=Value,Mode=TwoWay}" Margin="0,15,0,0"/>
    </StackPanel>
</Window>
```

## <i class="fa fa-cube" style="font-size:1em;"></i> WPFサンプル2（コレクション）
![w02.png](https://qiita-image-store.s3.amazonaws.com/0/142879/19afa3ba-6d46-9f00-570d-e2a303e6bb61.png)

```Xml:MainWindow.xaml
<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication2"
        xmlns:vm="clr-namespace:WpfApplication2.ViewModels"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <vm:PersonVM />
    </Window.DataContext>

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>

        <!-- 左側：そのまま表示 -->
        <ListBox Grid.Column="0" ItemsSource="{Binding Path=Persons}" DisplayMemberPath="Name" />

        <!-- 右側：表示をカスタマイズ -->
        <ListBox Grid.Column="1" ItemsSource="{Binding Path=Persons}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Text="{Binding Name}" FontWeight="Bold"/>
                        <TextBlock Text="{Binding Memo}"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Window>
```

```CSharp:PersonVM.cs
using System.Collections.Generic;
using WpfApplication2.Models;

namespace WpfApplication2.ViewModels
{
    public class PersonVM
    {
        // リスト内容の変更に対応する場合は
        // List の代わりに System.Collections.ObjectModel.ObservableCollection を使う
        public List<Person> Persons { get; set; }

        public PersonVM()
        {
            this.Persons = new List<Person>();

            this.Persons.Add(new Person { Name = "太郎", Age = 10, Memo = "あいうえお" });
            this.Persons.Add(new Person { Name = "次郎", Age = 8, Memo = "aaaa" });
            this.Persons.Add(new Person { Name = "三郎", Age = 3, Memo = "123456" });
        }
    }
}
```

```CSharp:Person.cs
namespace WpfApplication2.Models
{
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Memo { get; set; }
    }
}
```

## <i class="fa fa-cube" style="font-size:1em;"></i> WPFサンプル3（コンバーター）
![w03.png](https://qiita-image-store.s3.amazonaws.com/0/142879/0032428b-e2ea-0ca9-021b-d09d5612cea6.png)

```Xml:MainWindow.xaml
<Window x:Class="WpfApplication3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication3"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <!-- System.Windows.Controls.BooleanToVisibilityConverterクラス -->
        <BooleanToVisibilityConverter x:Key="BoolToVisibilityConv"/>

        <local:BooleanToMessageConverter x:Key="BoolToMsgConv"/>
    </Window.Resources>
    
    <StackPanel>
        <CheckBox x:Name="checkbox" Content="表示" IsChecked="True" Margin="0,15,0,0"/>
        
        <Button Content="ボタン" Visibility="{Binding ElementName=checkbox,Path=IsChecked,Converter={StaticResource BoolToVisibilityConv}}" Margin="0,15,0,0"/>
        
        <TextBlock Text="{Binding ElementName=checkbox,Path=IsChecked,Converter={StaticResource BoolToMsgConv}}" Margin="0,15,0,0"/>
    </StackPanel>
</Window>
```
```CSharp:BooleanToMessageConverter.cs
using System;
using System.Globalization;

namespace WpfApplication3
{
    /// <summary>
    /// 真偽値からメッセージへ変換
    /// </summary>
    public class BooleanToMessageConverter : System.Windows.Data.IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is bool && (bool)value)
            {
                return "Trueです。";
            }
            else
            {
                return "Falseです。";
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
```

# <i class="fa fa-cubes" style="font-size:1em;"></i> 動作確認した環境
* Windows 10 (バージョン1607), Visual Studio 2015

# <i class="fa fa-book" style="font-size:1em;"></i> 参考サイト
* [データ バインディング - MSDN](https://msdn.microsoft.com/ja-jp/windows/uwp/data-binding/index)
* [xBind マークアップ拡張 - MSDN](https://msdn.microsoft.com/windows/uwp/xaml-platform/x-bind-markup-extension)
* [データ バインド (WPF) - MSDN](https://msdn.microsoft.com/ja-jp/library/ms750612.aspx)