c# - 确定自定义 winforms 控件的设计时上下文

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

假设我有一个自定义 WinForms 控件:

public class MyBaseControl : Control
{
     ...
}

扩展如下:

public class MyControl : MyBaseControl
{
     ...
}

通过检查 this.DesignMode 属性标志,确定控件是否是可视化设计的相当简单,但是有没有办法确定 MyControl 本身正在被设计,而不是在设计时被操纵?


为了提供额外的说明,在 MyControl 类中,我尝试在设计组件本身时区分设计时:

"Control" designer

当组件在设计时从工具箱添加到表单时:

enter image description here

最佳答案

您可以检查该控件是否是设计器的根控件。
您可以获取IDesignerHost服务,然后检查RootComponent属性来查看您的控件是否是当前设计器的根组件。

using System.Windows.Forms;
using System.ComponentModel.Design;
public partial class MyBaseControl : UserControl
{
    public MyBaseControl()
    {
        InitializeComponent();
    }

    public bool IsRootDesigner
    {
        get
        {
            var host = (IDesignerHost)this.GetService(typeof(IDesignerHost));
            if (host != null)
                return host.RootComponent == this;

            return false;
        }
    }
}

关于c# - 确定自定义 winforms 控件的设计时上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35788673/

相关文章:

c# - 使用通用字典将值插入表

c# - SqlDataReader.GetValue 按列名获取数据的方法

c# - LINQ to SQL "aggregating"属性

.net - 如何让事件再次变空?

.net - 当启动时发生错误时,如何在显示 MessageBox 后立即退出 Windows 窗体应用程序?

c# - 使全屏 wpf 应用程序在所有分辨率下看起来都一样

c# - 异常捕获最佳实践 (c#/.net)

.net - 如何将 WSDL 添加到 Visual Studio 2005 项目?

c# - Azure 中的 ASP.NET MVC Core 应用程序

c# - "scroll"单行文本框