简体   繁体   English

更改继承的.net控件上的属性的DefaultValue

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

In .net, I have an inherited control: 在.net中,我有一个继承的控件:

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). 我只是想将DropDownStyle属性的默认值更改为另一个值(ComboBoxStyle.DropDownList),除了在基类(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. 但是,这种方法会使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. 在Visual Studio中设计自定义控件时,如果为DropDownStyle选择ComboBoxStyle.DropDown,则认为您选择的属性仍然是默认值(来自基本ComboBox类中的[DevaultValue()]),因此它不会将customComboBox.DropDownStyle = ComboBoxStyle.DropDown行添加到Designer.cs文件中。 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: 好吧,你不能覆盖DropDownStyle属性,因为它不是虚拟的,但你可以这样做:

[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). 我已经尝试了它,它似乎不正常,因为视觉工作室设计师也从这种方法混淆并强制ComboBoxStyle.DropDown(基类的默认值)。

Is there any other way to do this? 有没有其他方法可以做到这一点? Sorry for the verbose question, it is hard to describe in detail. 对于冗长的问题很抱歉,很难详细描述。

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;}
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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