C#のWPFでデータバインディング

WPFのC#アプリケーションを久しぶりに作ろうとしたら、XAMLでのデータバインディングをすっかり忘れてしまっていたので、メモっておきます。 試した環境は下記です。

  • Windows10

  • Visual Studio 2015 Express for Windows Desktop (C#)

テキストボックスにオブジェクトをバインドする

オブジェクトのプロパティをTextBoxにバインディングします。 作ってみたのは、2つのTextBoxの片方に文字列を入れるともう片方のTextBoxに同じ文字が表示されるというものです。 まず、XAMLは下記です。

<Window x:Class="trial_binding.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:trial_binding"
        mc:Ignorable="d"
        Title="MainWindow" Height="200" Width="200">
    <Grid>
        <StackPanel Name="stackpanel">
            <TextBox Name="textbox1" Text="{Binding Hoge, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="10" />
            <TextBox Name="textbox2" Text="{Binding Hoge, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="10" />
        </StackPanel>
    </Grid>
</Window>

TextBox要素のText属性ですが、Binding Hogeはデータソースを示し、Modeはバインディングの方向を示し、UpdateSoureceTriggerはデータをバインド先に適用するタイミングを示します。 コードは下記です。

using System.Windows;

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

            HogeClass HogeObject = new HogeClass();
            HogeObject.Hoge = "Try it.";
            stackpanel.DataContext = HogeObject;
        }
    }

    public class HogeClass
    {
        public string Hoge { get; set; }
    }
}

TextBlock要素の上位のStackPanelにバインドしました。(正しいのかな?) そして実行してみると、テキストボックスの文字を変えるともう一つのテキストボックスの文字も変わります。動画じゃないとわからないけど。 image0

公開日

広告