nprogram’s blog

気ままに、プログラミングのトピックについて書いていきます

WPFのデータ・バインディングの基礎学習 [C#][WPF]

WPFのデータバインディングを勉強していきます。

開発環境は、Microsoft Visual Studio Community 2015を使用します。

WPFでは、データ・ソース(=モデルなどの、データの提供元)をビュー(=WPFの場合はXAMLコード)上のUI要素と簡単に結び付けるために、データ・バインディングという仕組みを提供しています。

サンプルプロジェクトでは、バインディング要素は以下のような関係になっています。

項目 意味 サンプルでの対象
バインディングソース データの提供元のオブジェクト Slider Control
ソース・プロパティ データ提供元となる、バインディング・ソースのプロパティ Slider .Value
バインディングターゲット データの反映先のオブジェクト Label Control
ターゲットプロパティ データの反映咲となる、バインディング・ターゲットのプロパティ Labal Content

<サンプルプロジェクト> プロジェクトは、WPFプロジェクトを選択してください。

<サンプルプロジェクト(ModeプロパティがOneWayのとき)>

<Window x:Class="WPF_TEST.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:WPF_TEST"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <Slider x:Name="SampleSlider">
        </Slider>

        <Label Content="{Binding ElementName=SampleSlider, Path=Value}"></Label>

    </StackPanel>
</Window>

<サンプルプロジェクト(ModeプロパティがTwoWayのとき> UpdateSourceTriggerプロパティがPropertyChangedになっているのに注意してください

<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"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>

        <Slider x:Name="SampleSlider"/>

        <TextBox Text="{Binding ElementName=SampleSlider, Path=Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

    </StackPanel>
</Window>

<参考ページ> www.atmarkit.co.jp