[Silverlight]实现到自定义类型的属性数据绑定

  在当前的.NET程序中,会经常使用到数据绑定,因为使用数据绑定,可以大大简化一个常用过程——数据源发生变化,反应数据源的数据视图进行相应更新。谈及这个过程,很容易会联想起设计模式中的观察者模式,很明显,数据绑定的设计是这个模式的一种实现。本文使用以下例子说明如何在Silverlight或者WPF中实现到自定义数据类型的属性的数据绑定。

  现在有一个表单界面,上面要显示顾客的详细信息,包括名称,年龄,性别。

  以下是自定义类型Customer的代码:

代码
   public class Customer : INotifyPropertyChanged
{
private string m_name;
public string CustomerName
{
get { return m_name; }
set
{
if (m_name == value)
return ;

m_name
= value;

if (PropertyChanged != null )
PropertyChanged(
this , new PropertyChangedEventArgs( " CustomerName " ));
}
}

private byte m_age;
public byte Age
{
get { return m_age; }
set
{
if (m_age == value)
return ;

m_age
= value;

if (PropertyChanged != null )
PropertyChanged(
this , new PropertyChangedEventArgs( " Age " ));
}
}

private bool m_isMale;
public bool IsMale
{
get { return m_isMale; }
set
{
if (m_isMale == value)
return ;

m_isMale
= value;

if (PropertyChanged != null )
PropertyChanged(
this , new PropertyChangedEventArgs( " IsMale " ));
}
}

#region INotifyPropertyChanged Members

public event PropertyChangedEventHandler PropertyChanged;

#endregion
}

  上述的Customer类定义中,继承了INotifyPropertyChanged接口,该接口定义于System.ComponentModel命名空间。该接口只有一个成员,就是PropertyChanged事件。从粗体代码中可以看到,在Customer的三个属性的Set访问器中,都会触发PropertyChanged事件,而且每次的事件参数都以对应被赋值的属性名为参数。(注意Set访问器的验证代码,对于没有修改当前值的赋值,不会触发此事件)

  正是通过触发此事件,对Customer实例的数据绑定就能够顺利执行。

  以下是该表单的Silverlight控件代码:

  XAML:

代码
< UserControl x:Class ="SilverlightApplication5.MainPage"
xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"

 Loaded
="UserControl_Loaded" >
< StackPanel x:Name ="stp_customerInfo" >
< TextBlock x:Name ="tb_name" Text =" {Binding CustomerName} " FontSize ="18" />
< TextBlock x:Name ="tb_age" Text =" {Binding Age} " FontSize ="17" />
< TextBlock x:Name ="tb_sex" Text =" {Binding IsMale} " FontSize ="16" />

  
< Button x:Name ="btn_changeName" Content ="Change name to Foo" Click ="btn_changeName_Click" HorizontalAlignment ="Left" />
</ StackPanel >
</ UserControl >

   后端C#代码:

代码
public partial class MainPage : UserControl
{
public MainPage()
{

   InitializeComponent();

}

private void UserControl_Loaded( object sender, RoutedEventArgs e)
{
stp_customerInfo.DataContext
= new Customer() { CustomerName = " Agile " , Age = 18 , IsMale = true };
}

  
private void btn_changeName_Click( object sender, RoutedEventArgs e)
{
Customer c
= stp_customerInfo.DataContext as Customer;

c.CustomerName
= " Foo " ;
}

}

  上面的代码是一个非常简单的客户信息表单控件。在控件的Loaded事件中,为容器stp_customerInfo设置了一个硬编码的数据源,也就是一个Customer实例。而在容器中的三个TextBlock控件会继承这个数据源(当然也可以逐个TextBlock设置同一个Customer作为数据源)。运行该Silverlight程序会有以下结果:

[Silverlight]实现到自定义类型的属性数据绑定

然后,当点击按钮,从按钮的事件处理代码可以看到,该事件处理程序会获取原来已经设置的Customer实例,然后修改其CustomerName属性为"Foo"。点击按钮后的效果:

[Silverlight]实现到自定义类型的属性数据绑定

实现到自定义类型的属性数据绑定过程就是这样,手段很简单,但是使用价值很大。

你可能感兴趣的:(silverlight)