问题遇到的现象和发生背景
c# 自定义控件的属性,添加属性集合时不能被调用,但如果将属性类型设置为string类型就会正常调用。
问题相关代码,请勿粘贴截图
[Description("添加菜单项"), Category("自定义属性"), Browsable(true)]
public string MM { set { //测试属性设置时是否能够接收到信息
this.mm = value; //===这里设置断点,可以正常接收到信息====
} get { return mm; } }
[Description("添加菜单项"), Category("自定义属性"),Browsable(true)]
public List<Menu> Items { get { return menus; } set {
this.menus = value; //====这里设置断点,无法正常接收到信息(在下面图片中添加Menu对象都正常,但点击确定后,这里的断点不会被执行)====
foreach (var item in value)
{
this.AddMenu(item.Text, item.Image);
}
}
}
将控件导入到窗口中,在控件属性中添加数据,与ListView 添加数据完全不一样,不知道是不是Menu类中需要做什么调整
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
System.Windows.Forms.ListViewItem listViewItem1 = new System.Windows.Forms.ListViewItem("333333");
this.panel1 = new LeftMenu.LeftMenu();
this.listView1 = new System.Windows.Forms.ListView();
this.SuspendLayout();
//
// panel1
//
this.panel1.BackColor = System.Drawing.SystemColors.AppWorkspace;
this.panel1.Dock = System.Windows.Forms.DockStyle.Left;
this.panel1.Items = ((System.Collections.Generic.List<LeftMenu.Menu>)(resources.GetObject("panel1.Items")));
this.panel1.Location = new System.Drawing.Point(0, 0);
this.panel1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.panel1.MM = null;
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(200, 450);
this.panel1.TabIndex = 0;
//
// listView1
//
this.listView1.Items.AddRange(new System.Windows.Forms.ListViewItem[] {
listViewItem1});
this.listView1.Location = new System.Drawing.Point(453, 134);
this.listView1.Name = "listView1";
this.listView1.Size = new System.Drawing.Size(121, 97);
this.listView1.TabIndex = 1;
this.listView1.UseCompatibleStateImageBehavior = false;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 17F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.listView1);
this.Controls.Add(this.panel1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
运行结果及报错内容
添加的集合数据,在属性设置时,无法被获取。
我的解答思路和尝试过的方法
public class Menu{
//观察Menu可以正常被创建,但无论如何都不能在属性设置中获取到。
public Menu()
{
//this.button.Text = this.text;
this.button.Text = " 9" + this.text;
this.button.TextAlign = ContentAlignment.MiddleLeft;
if (this.image != null) this.button.Image = this.image;
this.button.ImageAlign = ContentAlignment.MiddleLeft;
this.button.Font = new Font(this.family, this.fontSize);
}
public Menu(string text)
{
this.text = text;
this.button.Text = " " + text;
this.button.TextAlign = ContentAlignment.MiddleLeft;
if (this.image != null) this.button.Image = this.image;
this.button.ImageAlign = ContentAlignment.MiddleLeft;
this.button.Font = new Font(this.family, this.fontSize);
}
}
我想要达到的结果
不知道ListView控件中的Items属性值是如何实现的,我需要达到这种功能。