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。