c# - 容器 UserControl - 处理和修改添加的控件

标签 c# winforms user-controls windows-forms-designer designer

我正在尝试创建一个自定义容器作为 UserControl

我的目标:我希望能够在设计器中拖动控件并在我的用户控件代码中处理传入的控件。

示例: 我将容器放在某处,然后添加一个按钮。在这一刻,我想让我的用户控件自动调整这个按钮的宽度和位置。这就是我卡住的地方。

我的代码:

[Designer("System.Windows.Forms.Design.ParentControlDesigner, System.Design", typeof(IDesigner))]
public partial class ContactList : UserControl
{
    public ContactList()
    {
        InitializeComponent();
    }        

    private void ContactList_ControlAdded(object sender, ControlEventArgs e)
    {
        e.Control.Width = 200;   // Nothing happens
        e.Control.Height = 100;  // Nothing happens

        MessageBox.Show("Test"); // Firing when adding a control
    }
}

enter image description here

enter image description here

MessageBox 运行良好。设置的 widthheight 被忽略。
问题只是“为什么?”。


编辑

我刚刚注意到,当放置按钮并使用 F6 重新编译时,按钮的大小被调整为 200x100。为什么这在放置时不起作用?

我的意思是... FlowLayoutPanel 会在您放置时立即处理添加的控件。这正是我要寻找的行为。

enter image description here

最佳答案

使用 OnControlAdded

要修复您的代码,当您将控件放在容器上并且您想要在 OnControlAdded 中设置一些属性时您应该使用 BeginInvoke 设置属性,这样控件的大小会改变,但大小句柄不会更新。然后要更新设计器,您应该使用 IComponentChangeService.OnComponentChanged 通知设计器有关更改控件大小的信息。 .

以下代码仅在您将控件添加到容器时执行。之后,它会根据您使用大小 handle 为控件设置的大小而定。它适合在设计时进行初始化。

protected override void OnControlAdded(ControlEventArgs e)
{
    base.OnControlAdded(e);
    if (this.IsHandleCreated)
    {
        base.BeginInvoke(new Action(() =>
        {
            e.Control.Size = new Size(100, 100);
            var svc = this.GetService(typeof(IComponentChangeService)) 
                          as IComponentChangeService;
            if (svc != null)
                svc.OnComponentChanged(e.Control, 
                   TypeDescriptor.GetProperties(e.Control)["Size"], null, null);
        }));
    }
}

关于c# - 容器 UserControl - 处理和修改添加的控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36481963/

相关文章:

c# - key 不存在错误

c# - XML 字符串数组反序列化

c# - 如何按名称引用 Windows 窗体控件 (C#/VB)

c# - ListView 中选中项的颜色

c# - 将事件处理程序传递给 UserControl 以分配给动态 LinkBut​​ton

c# - .NET Compact Framework 透明用户控件

c# - ASP.NET:由Nuget引起的.NET Framework/Standard/Core DLL冲突。 “您必须添加对程序集System.Runtime的引用...”

c# - ASP.NET:在资源管理器中重定向时 session 状态未更新

c# - 找不到类型或命名空间名称 'ListBoxItem'(是否缺少 using 指令或程序集引用?)

mvvm - 无法从主视图绑定(bind) UserControl