我正在尝试创建一个自定义容器作为 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
}
}
MessageBox
运行良好。设置的 width
和 height
被忽略。
问题只是“为什么?”。
编辑
我刚刚注意到,当放置按钮并使用 F6 重新编译时,按钮的大小被调整为 200x100。为什么这在放置时不起作用?
我的意思是... FlowLayoutPanel
会在您放置时立即处理添加的控件。这正是我要寻找的行为。
最佳答案
使用 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/