在向列表中添加对象时做一些事情
本文关键字:对象 列表 添加 | 更新日期: 2023-09-27 18:04:17
我创建了一个名为Postbox
的用户控件,其中包含一个公共的用户控件列表。
using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DocEngineManager
{
public partial class PostBox : UserControl
{
public PostBox()
{
InitializeComponent();
}
public List<PostBoxPost> Posts = new List<PostBoxPost>();
}
}
PostBoxPosts
是List中包含的UserControl的类型。
当用户在自己的应用程序中添加PostBoxPost
到Posts
列表时,我想在我的UserControl类中引发一个事件,知道添加了什么。
一个简单的列表不暴露任何事件,像ObservableCollection这样的东西可能对你有用?
public partial class PostBox : UserControl
{
public ObservableCollection<PostBoxPost> Posts = new ObservableCollection<PostBoxPost>();
public PostBox()
{
InitializeComponent();
Posts.CollectionChanged += OnPostsCollectionChanged;
}
private void OnPostsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null && e.NewItems.Count != 0)
{
foreach (PostBoxPost postBoxPost in e.NewItems)
{
// Do custom work here?
}
}
}
}