【问题标题】:Customise Controls at runtime在运行时自定义控件
【发布时间】:2011-08-06 09:00:19
【问题描述】:

我在表单上有控件,并在运行时使用程序集获取它的对象。现在我想在运行时更改它们的属性,例如前景色、背景色和文本。

private void button1_Click(object sender, EventArgs e)
{
    Type formtype = typeof(Form);
    foreach(Type type in Assembly.GetExecutingAssembly().GetTypes())
    {
        if (formtype.IsAssignableFrom(type))
        {
            listBox1.Items.Add(type.Name);
            Form frm = (Form)Activator.CreateInstance(type);
            foreach (Control cntrl in frm.Controls)
            {
                listBox1.Items.Add(cntrl.Name);
            }
        }
    }
}

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    Control cnt = (Control)listBox1.SelectedItem;
    MessageBox.Show(cnt.Name);
    cnt.ForeColor = colorDialog1.Color;
}

这段代码在运行时为我获取了对象,但是当我尝试更改前景色时,它给了我一个错误。谁能帮帮我?

【问题讨论】:

  • 我想在运行时更改控件的属性。
  • @Gapan 在此处发布您遇到的错误。没有人能在不知道问题的情况下帮助您。
  • 它不会产生任何错误但不会在运行时更改控件的属性...

标签: c# .net winforms


【解决方案1】:

您发布的代码有几个问题:

  1. listBox1.Items.Add(cntrl.Name); 您将控件名称而不是控件本身添加到集合中,listBox1.Items.Add(type.Name); 再次将表单类型名称添加到集合中。
  2. 在代码中:

    Form frm = (Form)Activator.CreateInstance(type);
    

    您每次都在创建一个新的 Form(s) 实例,并且没有在任何地方显示它们。

那么如何解决它:

private void button1_Click(object sender, EventArgs e)
{
    List<Control> controls = new List<Control>();

    Type formtype = typeof(Form);
    foreach (Type type in Assembly.GetExecutingAssembly().GetTypes())
    {
        if (formtype.IsAssignableFrom(type))
        {
            Form frm = (Form)Activator.CreateInstance(type);
            controls.Add(frm);//Add the new instance itself to the list
            foreach (Control cntrl in frm.Controls)
            {
                controls.Add(cntrl);
            }
            frm.Show();//show the new form created
        }
    }

    listBox1.DataSource = controls;
    listBox1.DisplayMember = "Name";//or "Text"
}

编辑:还要确保 colorDialog1 先前已初始化并显示为从中获取 colorDialog1.Color 值。

我不知道你想在这里实现什么,但如果你只想获取正在运行的表单的当前实例,你可以使用Form.ActiveForm 来实现......

【讨论】:

  • 如果我使用 listBox1.Items.Add(cntrl);而不是 listBox1.Items.Add(cntrl.Name);然后我得到与您的代码相同的输出。我的列表框控件没有获得控件名称。列表框填充了控件,但不显示它们的名称。当我调用 messagebox.show(cnt.name); 时,在列表框的选定索引更改事件中它显示选定的控件名称,但在 cnt.foreclor = colordialog1.color;它不会改变它的颜色
  • 当然颜色不会改变,您正在创建表单的新实例,而不是更新已经显示的实例..,还显示项目的名称。您可以使用数据绑定“我更新了答案以向您展示如何”。
  • 我想在运行时更改列表框控件中选定控件的属性可以吗?
  • 当然!我发布的代码在运行时更改列表框上控件的属性,没有任何问题。
  • 亲爱的 Jalal 我实现了您的代码,但它不起作用。请你给我解释一下...
猜你喜欢
  • 2016-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多