如何知道控件是在设计时还是运行时?

21

我有一个实现了ICustomTypeDescriptor接口的类(control),用于在设计时和运行时通过PropertyGrid进行自定义。我需要在设计时公开不同的属性(像widthheight等标准控件属性),在程序中使用PropertyGrid更改该控件的其他属性时则公开不同的属性。

我的代码如下:

class MyControl : UserControl, ICustomTypeDescriptor
{
    //Some code..

    public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
    {
        return GetProperties();
    }

    public PropertyDescriptorCollection GetProperties()
    {
        //I need to do something like this:
        if (designTime)
        { //Expose standart controls properties
            return TypeDescriptor.GetProperties(this, true);
        }
        else
        {
            //Forming a custom property descriptor collection
            PropertyDescriptorCollection pdc = new PropertyDescriptorCollection(null);
            //Some code..
            return pdc;
        }
    }
}

在C#中是否有类似于设计时标志的模拟器? 在条件编译方面是否更好?


1
你是在说 WPF 还是 WinForm? - Akash Kava
可能是 如何判断.NET代码是否由Visual Studio设计器运行 的重复问题。 - Peter Mortensen
3个回答

15

检查DesignMode属性是否为真或假。这是一个属于控件基类的属性。


2
实际上,它属于System.ComponentModel.Component基类。 - tafa
“'Component.DesignMode' 由于其保护级别而无法访问。”我该如何解决这个错误? - GuidoG
@GuidoG 不要从外部检查组件。控件必须自我检查。 - The incredible Jan

9
标志应该是 DesignMode。因此,您的代码应如下所示。
public PropertyDescriptorCollection GetProperties()
{
   //I need to do something like this:
   if (this.DesignMode)
   { //Expose standart controls properties
       return TypeDescriptor.GetProperties(this, true);
   }
   else
   {   //Forming a custom property descriptor collection
       PropertyDescriptorCollection pdc = new PropertyDescriptorCollection(null);
       //Some code..
       return pdc;      
   }
}

Here is the according MSDN doc.


我真的很讨厌冗余的“this”。 :) - The incredible Jan

3

使用基类的DesignMode属性。它可以告诉你模式信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接