简体   繁体   English

自定义TextBox出现错误,并检查Text属性

[英]Error with custom TextBox with checking of Text property

I'm writing a NumberTextbox , which extends the standard Textbox class of Winforms. 我正在编写一个NumberTextbox ,它扩展了Winforms的标准Textbox类。 The class includes the following override for the Text property: 该类包括Text属性的以下替代:

    [DefaultValue("")]
    public override string Text
    {
        get
        {
            return base.Text;
        }

        set
        {
            if (!IsNumber(value))
                throw new FormatException();
            base.Text = value;
        }
    }

The constructor does explicitly insert an empty string into the Text property. 构造函数确实将一个空字符串显式插入到Text属性中。 When I try to insert this textbox into a form using the designer, I get a FormatException . 当我尝试使用设计器将此文本框插入表单时,出现FormatException Replacing the throw line with a return; return;代替罚球线return; fixes the issue, but that seems to me to be wrong. 解决了这个问题,但是在我看来这是错误的。 Is there any better solution to this issue? 有没有更好的解决方案来解决这个问题? Note that the IsNumber method does return a true for the empty string. 请注意, IsNumber方法的确为空字符串返回true

Not sure why your IsNumber method not working properly in design mode. 不知道为什么IsNumber方法不能在设计模式下正常工作。 The simple way to address this is to not call the method if you are in design mode... 解决此问题的简单方法是,如果您处于设计模式,则不要调用该方法。

        set
        {
            if (!DesignMode && !IsNumber(value))
                throw new FormatException();
            base.Text = value;
        }

The designer works in mysterious ways its wonders to perform. 设计师以神秘的方式发挥其奇迹。 So occasionally you need to test for design mode to keep it working in my experience. 因此,有时您需要测试设计模式,以使其在我的经验中仍然有效。

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

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