Silverlight數據綁定實現用戶信息
Silverlight數據綁定的應用,在實際編程中是一個非常重要的操作步驟。對于初學者來說,在剛剛學習的過程中一定要牢固掌握好這方面的知識點,方便以后的應用。#t#
在本示例中我們將做一個簡單的Silverlight數據綁定,用來顯示用戶信息,XAML如下:
- < Grid x:Name="LayoutRoot"
Background="#46461F"> - < Grid.RowDefinitions>
- < RowDefinition Height="160">
- < /RowDefinition>
- < RowDefinition Height="40">
- < /RowDefinition>
- < RowDefinition Height="40">
- < /RowDefinition>
- < /Grid.RowDefinitions>
- < Grid.ColumnDefinitions>
- < ColumnDefinition Width="150">
- < /ColumnDefinition>
- < ColumnDefinition Width="*">
- < /ColumnDefinition>
- < /Grid.ColumnDefinitions>
- < Image Source="terrylee.jpg"
Width="78" Height="100" - HorizontalAlignment="Left"
Grid.Row="0" Grid.Column="1"/> - < TextBlock Foreground="White"
FontSize="18" Text="姓名:" - Grid.Row="1" Grid.Column="0"
HorizontalAlignment="Right"/> - < TextBlock x:Name="lblName"
Foreground="White" FontSize="18" - Grid.Row="1" Grid.Column="1"
HorizontalAlignment="Left"/> - < TextBlock Foreground="White"
FontSize="18" Text="位置:" - Grid.Row="2" Grid.Column="0"
HorizontalAlignment="Right"/> - < TextBlock x:Name="lblAddress"
Foreground="White" FontSize="18" - Grid.Row="2" Grid.Column="1"
HorizontalAlignment="Left"/> - < /Grid>
添加一個簡單User類,它具有Name和Address兩個屬性:
- public class User
- {
- public string Name
{ get; set; }- public string Address
{ get; set; }- }
使用Silverlight數據綁定句法{Binding Property}進行數據綁定,注意下面的兩個TextBlock控件Text屬性:
- < Grid x:Name="LayoutRoot"
Background="#46461F">- < Grid.RowDefinitions>
- < RowDefinition Height="160">
- < /RowDefinition>
- < RowDefinition Height="40">
- < /RowDefinition>
- < RowDefinition Height="40">
- < /RowDefinition>
- < /Grid.RowDefinitions>
- < Grid.ColumnDefinitions>
- < ColumnDefinition Width="150">
- < /ColumnDefinition>
- < ColumnDefinition Width="*">
- < /ColumnDefinition>
- < /Grid.ColumnDefinitions>
- < Image Source="terrylee.jpg"
Width="78" Height="100"- HorizontalAlignment="Left" Grid.
Row="0" Grid.Column="1"/>- < TextBlock Foreground="White"
FontSize="18" Text="姓名:"- Grid.Row="1" Grid.Column="0"
HorizontalAlignment="Right"/>- < TextBlock x:Name="lblName"
Foreground="White" FontSize="18"- Grid.Row="1" Grid.Column="1"
HorizontalAlignment="Left"- Text="{Binding Name}"/>
- < TextBlock Foreground="White"
FontSize="18" Text="位置:"- Grid.Row="2" Grid.Column="0"
HorizontalAlignment="Right"/>- < TextBlock x:Name="lblAddress"
Foreground="White" FontSize="18"- Grid.Row="2" Grid.Column="1"
HorizontalAlignment="Left"- Text="{Binding Address}"/>
- < /Grid>
指定數據源,注意這里是創建一個User的實例并賦值后,把user實例綁定到了TextBlock的DataContext上,而不是向之前我們所做的示例中那樣,直接指定Text屬性:
- private void UserControl_Loaded
(object sender, RoutedEventArgs e)- {
- User user = new User();
- user.Name = "TerryLee";
- user.Address = "中國 天津";
- lblName.DataContext = user;
- lblAddress.DataContext = user;
- }
上面這種Silverlight數據綁定模式,只是顯示數據而不對數據做任何修改,默認的綁定模式是一次綁定OneTime。