更改属性的默认值继承的.NET控件上 [英] Changing the DefaultValue of a property on an inherited .net control

查看:307
本文介绍了更改属性的默认值继承的.NET控件上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在.NET中,我有一个继承控制:

In .net, I have an inherited control:

public CustomComboBox : ComboBox

我只是想更改DropDownStyle属性的默认值,另一个值(ComboBoxStyle.DropDownList)除了在基类(ComboBoxStyle.DropDown)指定的默认​​1

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

但是,这种方法会混淆在Visual Studio设计。当设计在Visual Studio中的自定义控制,如果选择ComboBoxStyle.DropDown的DropDownStyle它认为你选择的物业仍是默认值(从[DevaultValue()在基ComboBox类),所以也没有一个customComboBox.DropDownStyle = ComboBoxStyle.DropDown行添加到Designer.cs文件。和混淆的话,你会发现屏幕不表现为预期的一次跑了。

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.

那么你不能覆盖DropDownStyle属性,因为它不是虚拟的,但你可以这样做:

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

但随后你会遇到使用新的声明的细微差别的麻烦。我已经尝试过了,它似乎并没有工作的权利作为Visual Studio的设计师会从这种做法也感到困惑和力量ComboBoxStyle.DropDown(默认为基类)。

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.

推荐答案

这看起来像它的工作原理:

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

这篇关于更改属性的默认值继承的.NET控件上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆