C# UserControl集合属性使用

在UserControl中,定义集合属性时,如果直接使用List是检测不到在属性框中的列表修改变化的,可以通过 ObservableCollection() 实现

1、定义类

 [Serializable]
    public class Menu : INotifyPropertyChanged
    {
        private string _Fa;

        public string MenuName
        {
            get { return _Fa; }
            set
            {
                if (_Fa != value)
                {
                    _Fa = value;
                    RaisePropertyChangedEvent("Fa");
                }
            }
        }

        private Image _Fb;

        public Image Image
        {
            get { return _Fb; }
            set
            {
                if (_Fb != value)
                {
                    _Fb = value;
                    RaisePropertyChangedEvent("Fb");
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void RaisePropertyChangedEvent(string name)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(name));
            }
        }
    
    }

2、实现

private ObservableCollection<Menu> _menus = new ObservableCollection<Menu>();
[Browsable(true)]
[Description("菜单")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public ObservableCollection<Menu> Menus
{
    get {  return _menus; }
    set {
        _menus = value;
        MessageBox.Show("ceshi");//这里检测不到
    }
}

private void FormHeader_Load(object sender, EventArgs e)
{
    GenerateUserPhoto();
    Menus.CollectionChanged += Menus_CollectionChanged; ;

}
private void Menus_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
    flowLayoutPanel1.Controls.Clear();
    for (int i = 0; i < Menus.Count; i++)
    {
        Button button=new Button();
        button.Text = Menus[i].MenuName;
        flowLayoutPanel1.Controls.Add(button);
    }
}

这样,在属性列表中修改Menus,显示区域就会实时变化,添加相应的菜单按钮个数。

原文地址:https://www.cnblogs.com/zhaogaojian/p/8630527.html