我创建了一个自定义 UserControl,我在设计时支持在其中拖放控件。我的控件正确地放入我的用户控件中,但是一旦放入用户控件中它们就会隐藏。要使添加的控件可见,我必须选择它并单击设计时 IDE 按钮“置于顶层”以查看添加的控件。当我重建解决方案时,控件再次隐藏。
我用下面的代码重现了这个问题。在 IDE 中,我创建了一个简单的用户控件“MyControl”,我向其中添加了一个停靠到“Fill”的面板控件。然后应该将该用户控件“MyControl”放到 Windows 面板上。然后,将另一个控件(例如 Label 或 Buton 控件)拖放到用户控件上,它就会隐藏。
下面是用户控件的代码。如何让在设计时放入用户控件的控件自动置于最前面?
MyControl.Designer.cs:
namespace Test
{
partial class MyControl
{
private System.ComponentModel.IContainer components = null;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.panel1 = new System.Windows.Forms.Panel();
this.SuspendLayout();
//
// panel1
//
this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel1.Location = new System.Drawing.Point(0, 0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(150, 150);
this.panel1.TabIndex = 0;
//
// MyControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.panel1);
this.Name = "MyControl";
this.ResumeLayout(false);
}
private System.Windows.Forms.Panel panel1;
}
}
MyControl.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.Design;
namespace Axiom.Controls
{
[Designer(typeof(ParentControlDesigner))]
public partial class MyControl : UserControl
{
public MyControl()
{
InitializeComponent();
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public Panel ContentPanel
{
get
{
return this.panel1;
}
}
}
internal class MyControlDesigner : ControlDesigner
{
public override void Initialize(IComponent component)
{
base.Initialize(component);
MyControl control = component as MyControl;
EnableDesignMode(control.ContentPanel, "ContentPanel");
}
}
}
更新:
我发现了另一个相关的问题/答案,解决了在设计时将控件拖放到自定义用户控件中的容器控件上的问题:
我遵循上述文章并在设计时成功地将工具箱控件拖放到自定义用户控件中的容器控件上。
最佳答案
问题其实很简单。您说您已经创建了一个 UserControl,然后向其添加了一个停靠以填充整个 UserControl 的 Panel 控件。
因此,每当您在设计时向 UserControl 添加控件时,您不是将它们添加到 Panel 控件,而是添加到 UserControl 本身。这导致它们被填充整个 UserControl 的 Panel 控件掩盖。
将它们置于最前面是一种临时解决方案,因为这会将它们置于面板控件之上。但是,它不会将它们放置在 Panel 控件中内部,这就是当您重建项目时它们再次“消失”的原因。它们实际上并没有消失,它们只是再次被 Panel 控件隐藏,因为默认的 Z 顺序排列使它们位于面板下方。
根本不清楚为什么需要 Panel 控件。如果它填满了整个 UserControl,它似乎没有任何作用。 UserControl 已经是容器控件,因此您不需要 Panel。尝试将其从您的 UserControl 中删除,然后您可以在设计时添加您想要的任何其他控件,而不会被停靠面板覆盖。
如果您绝对需要一个面板控件来填充您的用户控件,则需要添加一行代码,自动将在设计时拖放到用户控件上的控件添加到 Controls 中。 Panel 控件的集合。
关于c# - 将控件拖放到自定义用户控件上会隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5698051/