(读完此系列WPF和Silverlight的数据绑定问题你就轻松搞定)
1 Binding to List Data
前面都是绑定到一个对象,下面我们学习绑定到对象列表的方法。
我们还是先组织要绑定的数据,对象所对应的类还是Person,但新增了一个新类People,该类用来组织Person的列表.代码如下:
using System; using System.Collections.Generic; using System.ComponentModel;//INotifyPropertyChanged namespace SimpleDataBinding { class Person : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected void Notify(string PropName) { if (this.PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(PropName)); } } public Person() { _Age = 0; _name = "Null"; this.CurrentDate = DateTime.Now; } private string _name; public string Name { get { return _name; } set { if (value == _name) { return; } _name = value;//注意:不能用this.Name来赋值,如果这样形成循环调用,栈溢出 Notify("Name"); } } private int _Age; public int Age { get { return _Age; } set { if (value == _Age) return; _Age = value; Notify("Age"); } } public DateTime CurrentDate { get; set; } } //People类 class People : List<Person> { } } |
注意在同一命名空间下的代码最后添加了Perople类。
我们在UI里显示的XAML如下:
<Window x:Class="ListDataBinding.BindListDataTest" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:src="clr-namespace:ListDataBinding" Title="BindListDataTest" Height="113" Width="300"> <Window.Resources> <src:People x:Key="Family"> <src:Person Name="Jack" Age="18"/> <src:Person Name="Tom" Age="30"/> <src:Person Name="Jone" Age="14"/> <src:Person Name="Rose" Age="17"/> <src:Person Name="Mike" Age="13"/> </src:People> </Window.Resources> < |