上文主要介绍了Silverlight数据绑定的基本概念,以及示例了如何用OneWay的方式进行数据绑定,本文将介绍如何用TwoWay的方式绑定数据。用TwoWay方式绑定数据,绑定源同样也要实现 INotifyPropertyChanged接口.以下示例说明了TextBox元素的Text属性如何用TwoWay的方式来绑定;在 TwoWay 绑定中,对目标的更改会自动更新源,但绑定到 TextBox 的 Text 属性时除外。这种情况下,更新仅在 TextBox 失去焦点时发生。默认情况下是启动自动源更新的既UpdateSourceTrigger=Default,您可以禁用自动源更新,只在您选择的时间对源进行更新。例如,您可以这样做,以便在更新绑定数据源之前验证来自多个控件的用户输入。若要禁用自动源更新,请将 UpdateSourceTrigger 属性设置为 Explicit。此设置影响使用相同 Binding 对象的所有绑定(例如,在使用继承的数据上下文时)。但是,您必须为每个绑定单独更新源。若要更新某一绑定,请首先调用目标元素的 FrameworkElement.GetBindingExpression 方法,并且传递到目标 DependencyProperty 中。然后,可以使用返回值调用 BindingExpression.UpdateSource 方法。下面的示例代码演示了此过程。
MainPage.xaml:
<StackPanel Orientation="Vertical" Grid.Row="0">
<TextBlock Text="{Binding Title,Mode=OneWay}" Name="Title" Foreground="Black" Height="50" Width="100"/><!--OneWay方式绑定-->
<TextBlock Text="{Binding Price,Mode=TwoWay}" Name="Price" Foreground="Black" Height="50" Width="100"/> <!--TextBlock元素TwoWay方式绑定-->
<TextBox x:Name="Number" Text="{Binding Number,Mode=TwoWay,UpdateSourceTrigger=Explicit}" Height="40" Width="100"/> <!--TextBox元素TwoWay方式绑定,自动更新已设为禁用-->
<Button Grid.Row="1" Name="MyButton" Content="修改" Click="MyButton_Click" Width="40" Height="20"/>
</StackPanel>
MainPage.xaml.cs:
Technorati 标签: silverlight
Book book = new Book();
public MainPage()
{
InitializeComponent();
//给实体类赋值
book.Title = "Hello world";
book.Price = 80;
book.Number = 60;
//将数据绑定到绑定目标中
Title.DataContext = book;
Price.DataContext = book;
Number.DataContext = book;
}
private void MyButton_Click(object sender, RoutedEventArgs e)
{
//测试绑定源属性的更改是否会影响到绑定目标
book.Price = 50;
//获取绑定目标的依赖项属性
BindingExpression expression = Number.GetBindingExpression(TextBox.TextProperty);
//显示更新前的值
MessageBox.Show("Before UpdateSource, Number = " + book.Number);
//进行更新
expression.UpdateSource();
//显示更新后的值
MessageBox.Show("After UpdateSource, Number = " + book.Number);
}
book.cs:
//Book类实现了INotifyPropertyChanged接口
public class Book:INotifyPropertyChanged
{
private string _title;
public string Title
{
get { return _title; }
//set { _title = value; }
set { _title = value; NotifyPropertyChanged("_title");}
}
private int _number;
public int Number
{
get { return _number; }
set { _number = value;
NotifyPropertyChanged("_number");
}
}
private double _price;
public double Price
{
get { return _price; }
set { _price = value;
NotifyPropertyChanged("Price");
}
}
//用于通知绑定引擎源已更改的时间
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs(propertyName));
}
}
}
浙公网安备 33010602011771号