代码之家  ›  专栏  ›  技术社区  ›  Benny

字符串<->int/float在.NET WinForm中转换困难

  •  0
  • Benny  · 技术社区  · 15 年前

    WinForm上控件的文本属性总是字符串类型,所以如果我想为自定义控件公开其他类型的属性,我必须按以下步骤进行转换,如果我有几十个属性要公开,我会很痛苦。

      public int ImageGroupLength
        {
            get
            {
                return int.Parse(this.imageGroupLength.Text);
            }
            set
            {
                this.imageGroupLength.Text = value.ToString();
            }
        }
    

    那么,有没有优雅的方式来进行转换呢?

    3 回复  |  直到 15 年前
        1
  •  1
  •   Hans Passant    15 年前

    创建自己的控件是实现这一目标的方法。向项目中添加新类并粘贴下面显示的代码。编译。新控件显示在工具箱的顶部。您将希望实现badValue事件来警告用户输入的文本不合适。当Value属性更改时,ValueChanged可用于获取事件。

    using System;
    using System.Windows.Forms;
    
    class ValueBox : TextBox {
      public event EventHandler BadValue;
      public event EventHandler ValueChanged;
    
      private int mValue;
      public int Value {
        get { return mValue; }
        set {
          if (value != mValue) {
            mValue = value;
            OnValueChanged(EventArgs.Empty);
            base.Text = mValue.ToString();
          }
        }
      }
      protected void OnValueChanged(EventArgs e) {
        EventHandler handler = ValueChanged;
        if (handler != null) handler(this, e);
      }
      protected void OnBadValue(EventArgs e) {
        EventHandler handler = BadValue;
        if (handler != null) handler(this, e);
      }
      protected override void OnHandleCreated(EventArgs e) {
        base.OnHandleCreated(e);
        base.Text = mValue.ToString();
      }
      protected override void OnValidating(System.ComponentModel.CancelEventArgs e) {
        int value;
        if (!int.TryParse(base.Text, out value)) {
          SelectionStart = 0;
          SelectionLength = base.Text.Length;
          e.Cancel = true;
          OnBadValue(EventArgs.Empty);
        }
        else base.OnValidating(e);
      }
    }
    
        2
  •  1
  •   David Morton    15 年前

    您是否考虑过对文本框控件进行子类化,并将其简单地放在自定义控件上?您可以创建一个新属性来解析输入字符串并返回一个整数。

        3
  •  0
  •   Russ Clarke    15 年前

    不完全正确,但是你至少可以通过使用类似的东西来获得一些安全感。 当人们尝试将文本放入长度字段时,这将使您省去心痛!

    public int ImageGroupLength
    {
      get
      { 
        int ret;
        int.TryParse(this.imageGroupLength.Text, out ret);
    
        return ret; //Ret will be 0 if tryparse fails
      }
      set
      {
        ...
      }
    }