有人可以指出实现CollectionChanged的示例。我正在使用wpf mvvm light。我试着谷歌,没找到任何足够好的东西。
答案 0 :(得分:9)
public ObservableCollection<string> Names { get; set; }
public ViewModel()
{
names = new ObservableCollection<string>();
Names.CollectionChanged += this.OnCollectionChanged;
}
void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
//Get the sender observable collection
ObservableCollection<string> obsSender = sender as ObservableCollection<string>;
List<string> editedOrRemovedItems = new List<string>();
foreach(string newItem in e.NewItems)
{
editedOrRemovedItems.Add(newItem);
}
foreach(string oldItem in e.OldItems)
{
editedOrRemovedItems.Add(oldItem);
}
//Get the action which raised the collection changed event
NotifyCollectionChangedAction action = e.Action;
}
有关NotifyCollectionChangedEventArgs的更多信息,请查看here。
编辑:因为您需要添加/删除项目列表,所以我修改了示例代码。
答案 1 :(得分:1)
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
private ObservableCollection<Person> persons = new ObservableCollection<Person>();
public MainWindow()
{
InitializeComponent();
dgPerson.ItemsSource = persons;
persons.CollectionChanged += this.OnCollectionChanged;
}
void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
//Get the sender observable collection
ObservableCollection<Person> obsSender = sender as ObservableCollection<Person>;
NotifyCollectionChangedAction action = e.Action;
if (action == NotifyCollectionChangedAction.Add)
lblStatus.Content = "New person added";
if (action == NotifyCollectionChangedAction.Remove)
lblStatus.Content = "Person deleted";
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
Person p = new Person();
p.FirstName = txtFname.Text;
p.LastName = txtLname.Text;
persons.Add(p);
}