Is there a way to set the a default value for the attribute DesignerSerializationVisibility
for all the properties of a given class?
In practice, a way to switch the default behavior of black-listing the properties with a white-list approach.
Thanks
My preferance
You can provide default values for properties in constructor and decorate them using suitable
DefaultValue
attribute, then the designer will serialize them only if the value of them is different than default value.Also if you need to make them invisible at design-time, you can simply decorate them using
Browsable(false)
then they will not be shown at design time.Also you can check
DesignMode
in property setter to prevent setting a value for the property at design time and make it a run-time property.I also answer your question which you need to Not serialize properties that doesn't have DesignerSerializationVisibility attribute.
Not serialize properties that doesn't have DesignerSerializationVisibility attribute
As an option you can create a custom type descriptor for your component and using custom property descriptors which it returns, tell the designer to don't serialize properties that doesn't have
DesignerSerializationVisibility
.This way when you want the designer serialize a property you should decorate it with
DesignerSerializationVisibility
attribute withvisible
as value.Implemetaion
The designer ask the
PropertyDescriptor
of a property to decide to serialize the property. If theShouldSerialize
method of the descriptor returnstrue
it serializes the property, otherwise it doesn't serialize the property.To change this behavior you should override that method. To make the designer to use your property descriptor, you should register a custom
TypeDescriptionProvider
for your class. The provider should provide a customTypeDescriptor
for your class. The custom type descriptor should return a list of your newPropertyDescriptor
which you override that method.Important Note: To test the implementations, you should restart the visual studio.
TypeDescriptionProvider
Here we create a custom type description provider for our component. Then we will register the provider for our component.
TypeDescriptor
Here we implement our type descriptor which it's job is returning a list of our custom property descriptors.
PropertyDescriptor
Here is the implementation of our custom property descriptor. The implementation of most properties and methods is trivial. Only for
ShouldSerialize
method, we decide based on havingDesignerSerializationVisibility
Component
At last here is the component. As you see in the component code, we decorated a property (white list strategy) to be serialized. All other properties will not serialize because it's new behavior which we attached to our properties.