简体   繁体   English

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

[英]How to know whether a control is at design-time or not?

I have a class (control), implementing ICustomTypeDescriptor, which is used both at design-time and run-time by PropertyGrid for customization. 我有一个类(控件),实现了ICustomTypeDescriptor,它在设计时和PropertyGrid运行时都用于自定义。 I need to expose different properties at design-time (standard controls properties like width , height and so on) and at run-time, when PropertyGrid is used in my program to change other properties of that control. 我需要在设计时公开不同的属性(标准控件属性,如widthheight等),并在运行时,在我的程序中使用PropertyGrid来更改该控件的其他属性。

My code is like: 我的代码是这样的:

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;
        }
    }
}

Is there an analog for a design-time flag in C#? C#中的设计时标志是否有模拟? Is it maybe better to use conditional compilation? 使用条件编译可能更好吗?

Check if DesignMode is true or false. 检查DesignMode是true还是false。 It's a property that belongs to the control base class. 它是属于控件基类的属性。

The flag should be DesignMode . 标志应该是DesignMode Hence your code should look as follows 因此,您的代码应如下所示

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 . 这是相应的MSDN文档

Use the DesignMode property of the base. 使用基础的DesignMode属性。 This will tell you about the mode. 这将告诉您有关模式的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM