Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the DefaultValue of a property on an inherited .net control

In .net, I have an inherited control:

public CustomComboBox : ComboBox

I simply want to change the default value of DropDownStyle property, to another value (ComboBoxStyle.DropDownList) besides the default one specified in the base class (ComboBoxStyle.DropDown).

One might think that you can just add the constructor:

public CustomComboBox()
{
     this.DropDownStyle = ComboBoxStyle.DropDownList;
}

However, this approach will confuse the Visual Studio Designer. When designing the custom Control in Visual Studio, if you select ComboBoxStyle.DropDown for the DropDownStyle it thinks that the property you selected is still the default value (from the [DevaultValue()] in the base ComboBox class), so it doesn't add a customComboBox.DropDownStyle = ComboBoxStyle.DropDown line to the Designer.cs file. And confusingly enough, you find that the screen does not behave as intended once ran.

Well you can't override the DropDownStyle property since it is not virtual, but you could do:

[DefaultValue(typeof(ComboBoxStyle), "DropDownList")]
public new ComboBoxStyle DropDownStyle
{
      set { base.DropDownStyle = value; }
      get { return base.DropDownStyle; }
}

but then you will run into trouble from the nuances of using "new" declarations. I've tried it and it doesn't seem to work right as the visual studio designer gets confused from this approach also and forces ComboBoxStyle.DropDown (the default for the base class).

Is there any other way to do this? Sorry for the verbose question, it is hard to describe in detail.

like image 433
EMaddox84 Avatar asked Oct 02 '08 17:10

EMaddox84


1 Answers

This looks like it works:

public class CustomComboBox : ComboBox
{
    public CustomComboBox()
    {
        base.DropDownStyle = ComboBoxStyle.DropDownList;
    }

    [DefaultValue(ComboBoxStyle.DropDownList)]
    public new ComboBoxStyle DropDownStyle
    {
        set { base.DropDownStyle = value; Invalidate(); }
        get { return base.DropDownStyle;}
    }
}
like image 134
JC. Avatar answered Sep 30 '22 05:09

JC.