Silverlight單向綁定相關應用技巧解析
Silverlight開發(fā)工具是微軟公司在進軍UI領域的一個攻堅利器。它的出現(xiàn),改變了開發(fā)人員傳統(tǒng)的變成模式,使開發(fā)人員也能補通過美工來實現(xiàn)各種多媒體相關功能需求。在這里我們就先來了解下Silverlight單向綁定的一些相關概念。#t#
如果需要在數(shù)據(jù)源發(fā)生變化時能夠通知UI進行相應的更新,即使用Silverlight單向綁定OneWay或者雙向綁定TwoWay,則業(yè)務實體需要實現(xiàn)接口INotifyPropertyChanged。在本示例中,我們加上一個更新按鈕,當單擊按鈕時更新user實例的屬性值,會看到界面上的數(shù)據(jù)也會發(fā)生變化。
修改一下User類,使其實現(xiàn)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"));- }
- }
- }
- }
修改數(shù)據(jù)綁定模式,使用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這個工具的了解程度。