若有一WPF視窗包含以下XAML,Grid包含三個控制項TextBox、Label與TextBlock
<TextBox Height="23" HorizontalAlignment="Left" Margin="34,26,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" />
<Label Content="Label" Height="28" HorizontalAlignment="Left" Margin="34,68,0,0" Name="label2" VerticalAlignment="Top" Width="132" />
<TextBlock Height="23" HorizontalAlignment="Left" Margin="34,0,0,127" Name="textBlock1" Text="TextBlock" VerticalAlignment="Bottom" Width="125" />
</Grid>
利用Expression Blend 4,選取畫面上的Grid,從屬性視窗點選DataContext後方的「New」按鈕。
選取要繫結的自訂物件,以MyDataClass2為例:
Code:
public event PropertyChangedEventHandler PropertyChanged;
private string _MyProperty="";
public string MyProperty {
get { return _MyProperty; }
set {
if ( _MyProperty != value ) {
_MyProperty = value;
PropertyChanged ( this , new PropertyChangedEventArgs ( "MyProperty" ) );
}
}
}
}
按照相同的步驟為TextBlock和TextBox控制項的Text屬性進行相同的資料繫結設定。
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:wpfDataBinding" x:Class="wpfDataBinding._7_DataContext"
Title="_7_DataContext" Height="300" Width="300">
<Grid x:Name="grid1">
<Grid.DataContext>
<local:MyDataClass2/>
</Grid.DataContext>
<TextBox Height="23" HorizontalAlignment="Left" Margin="34,26,0,0" x:Name="textBox1" VerticalAlignment="Top" Width="120" />
<Label Content="{Binding MyProperty}" Height="28" HorizontalAlignment="Left" Margin="34,68,0,0" x:Name="label2" VerticalAlignment="Top" Width="132" />
<TextBlock Height="23" HorizontalAlignment="Left" Margin="34,0,0,127" x:Name="textBlock1" Text="{Binding MyProperty}" VerticalAlignment="Bottom" Width="125" />
</Grid>
</Window>