【问题标题】:How to control that dynamically added usercontrol?如何控制动态添加的用户控件?
【发布时间】:2017-01-10 08:28:05
【问题描述】:

我有这样的代码:

MyUserControl[] myControl = new MyUserControl[10];

表单加载时:

for( int i = 0; i < 10; i++ )
{
    myControl[i] = new MyUserControl();
    myControl[i].label1.Text = "Title";

    this.Controls.Add ( myControl[i] );
}

现在正常显示了。

然后按如下按钮:

private void Button1_Click(object sender, EventArgs e)
{
    myControl[0].label1.Text = "Other Title";
}

当我看到调试模式时,值已正常添加,但 lable1 文本未显示“其他标题”。

所以,我尝试了以下方法,但没有任何效果。

myControl[0].label1.Update();
myControl[0].label1.Invalidate();
myControl[0].label1.Refresh();

请多多指教。

【问题讨论】:

  • 也许你应该考虑设置 Location 属性,这样它们就不会都在彼此之上,你只能看到最上面的那个。很难猜,这样的问题应该很明显了。
  • 当我尝试它时效果很好。这是您唯一的初始化代码吗?因为当您没有分配正确的位置 (x,y) 时,它们似乎会相互重叠。
  • 工作正常!见this
  • 位置代码已存在。该代码是显示的简单示例。目前不工作。我只测试了一个用户控件,但它是相同的。我认为还有其他原因。

标签: c# winforms dynamic-usercontrols


【解决方案1】:

我不明白你的概念希望这个例子对你有用

private void Button1_Click(object sender, EventArgs e)
{
    //myControl[0].label1.Text = "Other Title";

    MyUserControl ctrl = null;
    foreach (var c in this.Controls)
    {
        if (c.GetType().Name == "MyUserControl")
        {
            var myctrl = (MyUserControl)c;
            if (myctrl.Text == "Title")
            {
                ctrl = myctrl;
                break;
            }
        }
    }
    if (ctrl != null)
    {
        ctrl.Text = "Other Title";
    }
}

这是一个非常简单的示例,代码可以正常工作,您必须根据需要进行增强

【讨论】:

  • 别忘了评论这篇文章
【解决方案2】:

谢谢大家。我找到了这件事的根本原因。

myControl[0].label1.Text = "Other Title";
myControl[0].BringToFront(); // <- Solved problem with this code.

我不知道为什么 z 顺序被扭曲了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-06
    • 2012-12-10
    • 1970-01-01
    • 2010-12-07
    • 1970-01-01
    相关资源
    最近更新 更多