SliverLight使用ObservableCollection和INotifyPropertyChanged绑定数据
ObservableCollection是动态的数据集合,当该集合增加、删除或者集合被刷新时,INotifyPropertyChanged会给客户端提供PropertyChanged的通知。
在silverlight中,创建数据源集合可以使用ObservableCollection类,ObservableCollection实现了INotifyPropertyChanged、INotifyCollectionChanged,可以触发PropertyChanged事件。
INotifyPropertyChanged的作用就是向客户端发出某一个属性值发生更改的通知。
下面将创建一个简单的slverlight应用程序,用DataGrid来呈现Name和Score,另外有一Chart来呈现同样的数据,两者的数据源都是相同的ObservableCollection对象。最后创建一timer来随机地为ObservableCollection增加一行或者为某人更改Score。
下面定义一个数据实体对象。
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;
namespace SLObservableCollection
{
public class User : INotifyPropertyChanged
{
#region Property
private string name;
public string Name
{
get { return name; }
set
{
if (value != name)
{
name = value;
onPropertyChanged(this, "Name");
}
}
}
private long score;
public long Score
{
get { return score; }
set
{
if (score != value)
{
score = value;
onPropertyChanged(this, "Score");
}
}
}
#endregion
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void onPropertyChanged(object sender, string propertyName)
{
if (this.PropertyChanged != null)
{
PropertyChanged(sender, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
}
定义数据集合:
ObservableCollection<User> GetUserCollection()
{
ObservableCollection<User> rVal = new ObservableCollection<User>();
rVal.Add(new User { Name = "Tom", Score = 2 });
rVal.Add(new User { Name = "ruth", Score = 3 });
rVal.Add(new User { Name = "sunfishlu", Score = 4 });
rVal.Add(new User { Name = "walle", Score = 5 });
rVal.Add(new User { Name = "john", Score = 6 });
return rVal;
}
XAML布局和绑定:
<Grid x:Name="LayoutRoot" Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="300" />
</Grid.RowDefinitions>
<sdk:DataGrid x:Name="dataGrid" Grid.Row="0">
</sdk:DataGrid>
<charting:Chart x:Name="chartControl" Grid.Row="1" Title="Live Chart">
<charting:Chart.Series>
<charting:ColumnSeries DependentValueBinding="{Binding Score}"
IndependentValueBinding="{Binding Name}" />
</charting:Chart.Series>
</charting:Chart>
</Grid>
最后我们在构造器中绑定数据到datagrid和chart:
public MainPage()
{
InitializeComponent();
users = GetUserCollection();
this.dataGrid.ItemsSource = users;
((DynamicSingleSeriesWithAxes)this.chartControl.Series[0]).ItemsSource = users;
timer = new Timer(timerFired, null, 10000, 2000);
}
效果图如下: