在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,顯示區域就會實時變化,添加相應的菜單按鈕個數。