如何知道控件是否在设计时?

Vas*_*sya 16 .net c# design-time

我有一个类(控件),实现了ICustomTypeDescriptor,它在设计时和PropertyGrid运行时都用于自定义.我需要在设计时公开不同的属性(标准控件属性width,height等等),并在运行时,在我的程序中使用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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

C#中的设计时标志是否有模拟?使用条件编译可能更好吗?

Dev*_*erX 12

检查DesignMode是true还是false.它是属于控件基类的属性.

  • 实际上,它属于`System.ComponentModel.Component`基类. (2认同)

Jur*_*uri 8

国旗应该是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;      
   }
}
Run Code Online (Sandbox Code Playgroud)

这是相应的MSDN文档.