views:

153

answers:

1

Hi,

I'm building a custom web control with a public property which I only want to be available in design time (i.e. make it unavailable in code behind). The DesignOnly attribute promises to do just that, but when I set [DesignOnly(true)] it has no noticeable effect whatsoever:

[Bindable(true)]
[Category("Appearance")]
[DefaultValue(null)]
[Localizable(false)]
[DesignOnly(true)]
public string MyProp
{
    get
    {
        return ViewState["MyProp"] as string;
    }


    set
    {
        ViewState["MyProp"] = value;
    }
}

The property still appears in code behind IntelliSense. Setting a value to it in code behind works. In these respects, the behavior is just as if the attribute had never been set. And I've cleaned and rebuilt the complete solution. Twice.

Am I doing it wrong? Can you please tell me what is the right way to go about this, then?

Many thanks in advance.

+1  A: 

The DesignOnly attribute promises to do just that

Actually, no; it tries to make it clear when accessing it in code isn't available; if you lie (i.e. claim that something is design-only when it is available) then you should expect it to misbehave. The compiler knows what is available, and this design-only attribute is not defined in the C# spec, so it makes no difference to the compiler if you add this attribute.

Try adding:

[EditorBrowsable(EditorBrowsableState.Never)]

which the code editor (IDE) looks at (but only when using a separate assembly) - note that this doesn't stop you using it - it just hides it.

I believe the MSDN text is trying to describe the difference between properties that actually exist on code, vs properties that only pretend to exist; you can actually do all sorts of things to make fake properties appear in the designer, and it is these pretend properties that might be marked as design-only.

Marc Gravell
Thanks! That was enlightening. So I gather that there's no way to control the actual availability of a property in a way which is dependent on the current mode (design/runtime)?
AviJ
You can make code properties unavailable to most designers by using things like `[Browsable(false)]`; and you can make *true* designer-only properties by using a custom property model, but that is an advanced topic and involves understanding `TypeDescriptor`, `PropertyDescriptor`, `ICustomTypeDescriptor`, `TypeConverter`, etc- - very complex.
Marc Gravell