一步一步学Silverlight :数据绑定
单向绑定示例
如果需要在数据源发生变化时能够通知UI进行相应的更新,即使用单向绑定OneWay或者双向绑定TwoWay,则业务实体需要实现接口INotifyPropertyChanged。在本示例中,我们加上一个更新按钮,当单击按钮时更新user实例的属性值,会看到界面上的数据也会发生变化。
修改一下User类,使其实现INotifyPropertyChanged接口。
public class User : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private string _name; public string Name { get { return _name; } set { _name = value; if(PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Name")); } } } private string _address; public string Address { get { return _address; } set { _address = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Address")); } } } }
修改数据绑定模式,使用单向绑定OneWay模式,如{Binding Address, Mode=OneWay}
<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"/> <Button x:Name="btnUpdate" Width="100" Height="40" Content="Update" Click="btnUpdate_Click"/> <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, Mode=OneWay}"/> <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, Mode=OneWay}"/> </Grid>
编写事件处理程序,为了演示把user声明为一个全局的,并在按钮的单击事件中修改其属性值:
public partial class Page : UserControl { public Page() { InitializeComponent(); } User user; private void UserControl_Loaded(object sender, RoutedEventArgs e) { user = new User(); user.Name = "TerryLee"; user.Address = "中国 天津"; lblName.DataContext = user; lblAddress.DataContext = user; } private void btnUpdate_Click(object sender, RoutedEventArgs e) { user.Name = "李会军"; user.Address = "China Tianjin"; } }
运行后如下所示:
单击Update按钮后: