C# 在将对象添加到列表时做一些事情

C# Do something while adding object to list

我创建了一个名为 Postbox 的用户控件,其中包含一个 public 用户控件列表。

这是我的代码:

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 的 class 中引发事件并知道添加了什么。

一个简单的列表不会公开任何事件,像 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?
            }
        }
    }
}