バインディングは、ターゲットのプロパティにバインディング用のXAMLマークアップ拡張を埋め込みます。
Bindingマークアップ拡張にはさまざまなプロパティがあり、データ・バインディングの挙動を細かく設定することができます。
{Binding Path=SourcePropertyName}
なお、下記のようにPathプロパティは省略形で書くことができます。
{Binding SourcePropertyName}
Modeプロパティは、データ・バインディングの向きとタイミングを指定できます。
OneTime | UI要素生成時に一度だけ、ソース・プロパティの値を読み出してターゲット・プロパティに与える。 |
OneWay | ソース・プロパティが変更された際に、ターゲット・プロパティに変更を反映される(ターゲットの変更は無視)。 |
OneWayToSource | ターゲット・プロパティが変更された際に、ソース・プロパティに変更を反映される。 |
TwoWay | ソース・プロパティとターゲット・プロパティの双方の変更が反映される。 |
ModeプロパティでTwoWayやOneWayToSourceを指定した際には、変更をソース・プロパティに反映させるタイミングをUpdateSourceTriggerプロパティで指定できます
Default | バインディング・ターゲットの依存関係プロパティのメタデータに基づいてタイミングを決定する。 |
PropertyChanged | バインディング・ターゲットの値が変化する毎に変更を通知する。 |
LostFocus | バインディング・ターゲットの要素がフォーカスを失うたびに変更を通知する。 |
Explicit | 明示的にUpdateSourceメソッドを呼び出した場合にのみ変更を通知する。 |
xamlファイルのみでバインディング動作を確認できます。
<Window x:Class="WpfDevelop.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" mc:Ignorable="d" Title="MainWindow" Height="280" Width="320"> <Grid Background="DarkGray"> <Grid.RowDefinitions> <RowDefinition Height="2*"/> <RowDefinition Height="1*"/> </Grid.RowDefinitions> <TextBlock FontSize="18pt" Grid.Row="0" Margin="1" Text="{Binding ElementName=textBox, Path=Text}"/> <TextBox Name="textBox" Grid.Row="1" Margin="1" FontSize="18pt" Text="テキストを入力してください"/> </Grid> </Window>
<Window x:Class="WpfDevelop.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" mc:Ignorable="d" Title="MainWindow" Height="280" Width="320"> <StackPanel VerticalAlignment="Center"> <Slider Name="slider1" Width="200"/> <TextBox Width="80" Text="{Binding ElementName=slider1, Path=Value}"/> </StackPanel> </Window>