WPF ObservableCollection 使用方法
WPF提供一个强大的类(ObservableCollection )可以简化我们对界面集合显示的增删改操作,并且无刷新,这无疑是对用户对我们程序员都非常有用的。
当ObservableCollection<T>添加一行时,会自动通知绑定该ObservableCollection<T>的控件并做相应修改。如果希望当ObservableCollection<T>中的属性发生改变时通知UI,则T也需要继承于INotifyPropertyChanged。
首先声明实体类
public class Student : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private string _SID; public string SID { get { return _SID; } set { _SID = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("SID")); } } } private string _SName; public string SName { get { return _SName; } set { _SName = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("SName")); } } } private string _Address; public string SAddress { get { return _Address; } set { _Address = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("SAddress")); } } } }
实体类必须实现PropertyChangedEventHandler 事件这个是更新所需要的
接下来我们添加一个简易的界面
<Grid> <StackPanel> <DataGrid Name="dgStudent" Height="200" CanUserAddRows="False" MouseLeftButtonUp="dgStudent_MouseLeftButtonUp"></DataGrid> <StackPanel > <TextBox Name="txtid"></TextBox> <TextBox Name="txtname"></TextBox> <TextBox Name="txtaddress"></TextBox> <Button Name="btnAdd" Content="添加" Click="btnAdd_Click"></Button> <Button Name="btnUpdate" Content="编辑" Click="btnUpdate_Click"></Button> <Button Name="btnDelete" Content="删除" Click="btnDelete_Click"></Button> </StackPanel> </StackPanel> </Grid>
界面很粗糙,随意弄得
下面我们看看实现添加 编辑 删除的方式
public ObservableCollection<Student> datalist = new ObservableCollection<Student>(); private void Window_Loaded(object sender, RoutedEventArgs e) { dgStudent.ItemsSource = datalist; } private void btnAdd_Click(object sender, RoutedEventArgs e) { Student s = new Student(); s.SID = txtid.Text; s.SName = txtname.Text; s.SAddress = txtaddress.Text; datalist.Add(s); } private void btnUpdate_Click(object sender, RoutedEventArgs e) { foreach (var item in datalist) { if (item.SID == txtid.Text) { item.SName = txtname.Text; item.SAddress = txtaddress.Text; } } } private void btnDelete_Click(object sender, RoutedEventArgs e) { var ca = (Student)this.dgStudent.SelectedItem; datalist.Remove(ca); } private void dgStudent_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { var ca = (Student)this.dgStudent.SelectedItem; if (ca != null) { txtid.Text = ca.SID; txtname.Text = ca.SName; txtaddress.Text = ca.SAddress; } }
这样就实现的我们对于datagrid的添加删除修改等操作.比较以前,是不是方便多了。
我参考了eaglenet 的文章学习的
http://www.cnblogs.com/zhangjianli/archive/2012/06/01/2529864.html