Silverlight开发工具是微软公司在进军UI领域的一个攻坚利器。它的出现,改变了开发人员传统的变成模式,使开发人员也能补通过美工来实现各种多媒体相关功能需求。在这里我们就先来了解下Silverlight单向绑定的一些相关概念。#t#
如果需要在数据源发生变化时能够通知UI进行相应的更新,即使用Silverlight单向绑定OneWay或者双向绑定TwoWay,则业务实体需要实现接口INotifyPropertyChanged。在本示例中,我们加上一个更新按钮,当单击按钮时更新user实例的属性值,会看到界面上的数据也会发生变化。
修改一下User类,使其实现INotifyPropertyChanged接口。
- public class User : INotify
PropertyChanged- {
- public event PropertyChangedEven
tHandler PropertyChanged;- private string _name;
- public string Name
- {
- get { return _name; }
- set
- {
- _name = value;
- if(PropertyChanged != null)
- {
- PropertyChanged(this, new Property
ChangedEventArgs("Name"));- }
- }
- }
- private string _address;
- public string Address
- {
- get { return _address; }
- set
- {
- _address = value;
- if (PropertyChanged != null)
- {
- PropertyChanged(this, new Property
ChangedEventArgs("Address"));- }
- }
- }
- }
修改数据绑定模式,使用Silverlight单向绑定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";
- }
- }
Silverlight单向绑定的应用方法就为大家介绍这里,希望能帮助大家提高对Silverlight这个工具的了解程度。