【问题标题】:usercontrol adding another usercontrol programmatically in design time用户控件在设计时以编程方式添加另一个用户控件
【发布时间】:2011-08-14 20:20:42
【问题描述】:

我有一个用户控件 (UC1),它在设计时根据用户想要显示的内容更改外观。

  • 一个常规按钮,弹出一个带有用户控件 UC2 的窗口(该窗口仅在运行时显示)
  • UC2 直接托管在 UC1 中(常规按钮不显示)

由于我想在这两种情况下使用相同的 UC2 实例,我只是在 UC1 和表单之间转移所有权。

public UC1 ()
{
    _uc2 = new UC2 ();
}

public bool DisplayModeSimple
{
    get { return _displayModeSimple; }
    set
    {
        _displayModeSimple = value;
        if (_displayModeSimple)
        {
            // ... Verify if _uc2 is already in Controls...
            Controls.Remove (_uc2);
            uiButton.Visible = true;
        }
        else
        {
            // ... Verify that _uc2 is not in Controls ...
            Controls.Add (_uc2);
            uiButton.Visible = false;
        }
    }
}

private void HandleButtonClick (object sender, EventArgs e)
{
    // Not called if DisplayModeSimple=false since button is hidden...
    using (var form = new PopupForm (_uc2))
    {
        form.ShowDialog (this);
    }
}

在设计模式和运行时模式下都能正常工作。

在设计模式下,如果我更改显示模式,UC1 会正常运行。

但是,UC2 上的控件可以像在运行时一样单击。 如果我随后关闭托管 UC1 的表单并重新打开它,一切都会恢复正常,即,我无法“单击”UC2 中的任何控件。

【问题讨论】:

    标签: winforms user-controls windows-forms-designer


    【解决方案1】:

    问题是您的第一个 UserControl 托管在 VS 上,因此它知道处于设计模式。第二个 UserControl 托管在第一个 UserControl 中,因此它的宿主不是设计器,它认为是在一个普通容器中并相应地运行。如何解决这个问题有点棘手,因为没有简单的解决方案 AFAIK。 Here 你可以找到一些解决方法。另一种方法是递归测试 Site.DesignMode,但这取决于控件的深度。

    【讨论】:

    • 好的,我已经知道测试设计模式,但它没有帮助,因为我没有地方可以测试这个标志并强制 UC2 处于“设计模式”。此外,UC1(显示 UC2)在设计器中显示托管表单时表现正常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-17
    • 1970-01-01
    • 2010-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-15
    相关资源
    最近更新 更多