TextBlockコントロールにデータをバインディングする - XAMLによるデータバインディング
TextBlockコントロールにデータをバインディングします。コントロールへのバインディングをXAMLで設定します。
UI
WPFアプリケーションを作成します。メインのフォームにTextBlockを配置します。
コード
以下のコードを記述します。
Bird.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WpfBinding4
{
public class Bird
{
public string Name
{
get;
set;
}
}
}
解説
データを保存するクラスです。Nameプロパティを定義します。
MainWindow.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfBinding4
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Bird bird = new Bird();
bird.Name = "Pigion";
this.DataContext = bird;
}
}
}
解説
データ保存クラスのインスタンスを作成し、Nameプロパティを設定します。その後DataContextプロパティにクラスのインスタンスを設定します。
MainWindow.xaml
<Window x:Class="WpfBinding4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="224" Width="525">
<Grid>
<TextBlock Height="19" HorizontalAlignment="Left" Margin="12,12,0,0" Name="textBlock1"
Text="{Binding Path=Name}" VerticalAlignment="Top" Width="180" />
</Grid>
</Window>
解説
TextBlockのTextプロパティをBinding設定に変えます。
{Binding Path=Name}
Pathには用いるデータのパスを設定します。今回はBirdクラスのNameプロパティをバインドするデータに用いますのでNameを設定します。
Pathは省略できるため、
<TextBlock Height="19" HorizontalAlignment="Left" Margin="12,12,0,0" Name="textBlock1"
Text="{Binding Path=Name}" VerticalAlignment="Top" Width="180" />
部分を
<TextBlock Height="19" HorizontalAlignment="Left" Margin="12,12,0,0" Name="textBlock1"
Text="{Binding Name}" VerticalAlignment="Top" Width="180" />
と記述できます。
実行結果
アプリケーションを実行します。TextBlockのテキストにバインドされたデータが表示されます。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用