Silverlight学习之【最简单数据绑定示例】

在 Silverlight 中支持3种绑定:OneWay, TwoWay, OneTime. 默认是 OneWay.

  其中 OneWay 表示仅仅从数据源绑定到目标(通常是 UI 对象),单向的;

  TwoWay 表示既可以从数据源绑定到目标,目标的更改也可以反馈给数据源,使其发生更新。

  而 OneTime 是 OneWay 的一种特例,仅加载一次数据。随后数据的变更不会通知绑定目标对象。这样,可以带来更好的性能。

  绑定的语法可以用大括号表示,下面是几个例子:

<TextBlockText="{Binding Age}"/>

 

  等同于:

<TextBlock Text="{Binding Path=Age}" />

 

  或者显式写出绑定方向:

<TextBlock Text="{Binding Path=Age, Mode=OneWay}" />

 

  按照数据绑定的语义,默认是 OneWay 的,也就是说如果后台的数据发生变化,前台建立了绑定关系的相关控件也应该发生更新。

  比如我们可以将文章 (1) 中提到的数据源改为当前页面的一个私有成员,然后在某个 Button 点击事件中更改其中的值。代码如下:

public partial class Page : UserControl
  {
    private List<Person> persons;
    public Page()
    {
      InitializeComponent();

      persons = new List<Person>();
      for(var i=0; i< 5; i++)
      {
        persons.Add(new Person {Name = "Person " + i.ToString(), Age = 20 + i});
      }
      list1.DataContext = persons;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
      persons[0].Name = "Tom";
    }
  }

 

<ListBox x:Name="list1">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Age}" Margin="20,0" />
                        <TextBlock Text="{Binding Name}" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

 

  但是我们点击 Button 发现 ListBox 里的数据并没有发生变化。这是因为在数据源更新时,并没有发出任何通知。

  我们可以让数据源中的对象实现 INotifyPropertyChanged 接口,在绑定的源属性值发生变化时,发出相关的通知信息。

  代码如下:

public class Person: INotifyPropertyChanged
  {
    private int age;
    public int Age
    {
      get
      {
        return age;
      }
      set
      {
        age = value;
        NotifyPropertyChange("Age");
      }
    }

    private string name;
    public string Name 
    {
      get
      {
        return name;
      }
      set
      {
        name = value;
        NotifyPropertyChange("Name");
      }
    }
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChange(string propertyName)
    {
      if(PropertyChanged != null)
      {
        PropertyChanged(thisnew PropertyChangedEventArgs(propertyName));
      }
    }
  }

  这个代码的原理很简单,这里就不解释了。这样以后,点击按钮,前台的 ListBox 中第一条数据的人名就变成了 Tom:

  

listbox3

 

  http://www.cnblogs.com/RChen/archive/2008/07/03/1235039.html

  本文来自cpcpc的博客,原文地址:http://blog.csdn.net/cpcpc/article/details/6900418

posted @ 2011-11-03 21:14  niky  阅读(409)  评论(0编辑  收藏  举报