Arvo Bowen Arvo Bowen - 1 month ago 10
C# Question

How can I force a property value on a derived object?

I want to create a class that derives from a ListView object.

class MyListView : ListView
{
}


I have tried a few things to force the default
View
property but nothing I seem to do has any effect in the properties of the object during design time.

Some of the things I have tried are...

public MyListView():base()
{
base.View = View.Tile;
}

[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[DefaultValue(View.Tile)]
new public View View
{
get {
return base.View;
}
set {
base.View = value;
}
}

protected override void InitLayout()
{
base.InitLayout();
base.View = View.Tile;
}


So my question is how can I either force a value to always be persistent on the
View
property or how can I set a default value for it and hide the property in my new class?

Answer

In normal cases it's enough to override the property and put your desired value in both getter and setter. But View property of the ListView is a special case. the ListViewDesigner adds a shadowed View property to the designer.

If you take a look at ListViewDesigner class, you will see regardless of your new View property, the designer uses View property of the base class: ((ListView) base.Component).View = value;.

What can we do to force the ListView to use a specific View in design-time?

You can decorate your new View property with Browsable(false). This way it doesn't show the View property in property grid, but it shows the property in the control action list.

To remove that action list, you can register a different Designer for your control, for example ControlDesigner:

[Designer(typeof(ControlDesigner))]
public class MyListView : ListView
{
    public MyListView()
    {
        this.View = System.Windows.Forms.View.Tile;
    }
    [Browsable(false)]
    new public View View
    {
        get
        {
            return System.Windows.Forms.View.Tile;
        }
        set
        {
            base.View = System.Windows.Forms.View.Tile;
        }
    }
}

Also as another option instead of registering new designer for control, you can get the designer instance for the control and clear its action lists.

Don't forget to add reference to System.Design.dll and add using System.Windows.Forms.Design;

Comments