简体   繁体   中英

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. 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.

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#? Is it maybe better to use conditional compilation?

Check if DesignMode is true or false. It's a property that belongs to the control base class.

The flag should be 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 .

Use the DesignMode property of the base. This will tell you about the mode.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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