一.新建Model,User.cs类,继承INPC接口
public class User : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _age;
public string Age
{
get { return _age; }
set
{
_age = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Age"));
}
}
}
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Name"));
}
}
}
private string _sex;
public string Sex
{
get { return _sex; }
set
{
_sex = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Sex"));
}
}
}
}
二.XAML代码
<Window x:Class="ObservableCollectionDemo.MainWindow"
Title="MainWindow" Height="450" Width="800">
<Grid>
<StackPanel>
<DataGrid Name="dgUser" Height="200" MouseLeftButtonUp="dgStudent_MouseLeftButtonUp"></DataGrid>
<StackPanel >
<TextBox Name="txtName" ></TextBox>
<TextBox Name="txtAge" ></TextBox>
<TextBox Name="txtSex" ></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>
</Window>
三.后台代码:
namespace ObservableCollectionDemo
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Loaded += Window_Loaded;
}
public ObservableCollection<User> datalist = new ObservableCollection<User>();
private void Window_Loaded(object sender, RoutedEventArgs e)
{
dgUser.ItemsSource = datalist;//绑定ItemSource,使用ObervableCollection
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
User user = new User();
user.Name = txtName.Text;
user.Age = txtAge.Text;
user.Sex = txtSex.Text;
datalist.Add(user);
}
private void btnUpdate_Click(object sender, RoutedEventArgs e)
{
foreach (var item in datalist)
{
if (item.Name == txtName.Text)
{
item.Age = txtAge.Text;
item.Sex = txtSex.Text;
}
}
}
private void btnDelete_Click(object sender, RoutedEventArgs e)
{
var ca = (User)this.dgUser.SelectedItem;
datalist.Remove(ca);
}
//单机选中一行,修改下方编辑窗的内容
private void dgStudent_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
var selectUser = (User)this.dgUser.SelectedItem;
if (selectUser != null)
{
txtName.Text = selectUser.Name;
txtAge.Text = selectUser.Age;
txtSex.Text = selectUser.Sex;
}
}
}
}