2

WinForms NumericUpDown 允许我们使用 Select(Int32, Int32) 方法选择其中的文本范围。有什么方法可以设置/检索所选文本的起点、所选字符数和所选文本部分,就像我们可以使用 SelectionStart、SelectionLength 和 SelectedText 属性对其他类似文本框的控件执行此操作一样?

4

3 回答 3

5

NumericUpDown 控件具有可从控件集合访问的内部 TextBox。它是集合中 UpDownButtons 控件之后的第二个控件。由于 WinForms 不再处于开发阶段,因此可以肯定地说 NumericUpDown 控件的底层架构不会改变。

通过从 NumericUpDown 控件继承,您可以轻松地公开这些 TextBox 属性:

public class NumBox : NumericUpDown {
  private TextBox textBox;

  public NumBox() {
    textBox = this.Controls[1] as TextBox;
  }

  public int SelectionStart {
    get { return textBox.SelectionStart; }
    set { textBox.SelectionStart = value; }
  }

  public int SelectionLength {
    get { return textBox.SelectionLength; }
    set { textBox.SelectionLength = value; }
  }

  public string SelectedText {
    get { return textBox.SelectedText; }
    set { textBox.SelectedText = value; }
  }
}
于 2013-11-08T14:33:29.110 回答
1

与 LarsTech 的回答类似,您可以快速将NumericUpDown.Controls[1]as aTextBox转换为访问这些属性,而无需创建新类。

((TextBox)numericUpDown1.Controls[1]).SelectionLength; // int
((TextBox)numericUpDown1.Controls[1]).SelectionStart; // int
((TextBox)numericUpDown1.Controls[1]).SelectedText; // string
于 2017-08-26T00:18:20.633 回答
0

这对于普通的 NumericUpDown 控件是不可能的。

在本文中,作者解释了他如何将 NumericUpDown 控件子类化以公开底层 TextBox 对象,从而公开“缺失”的属性:

http://www.codeproject.com/Articles/30899/Extended-NumericUpDown-Control

他使用反射来获得对底层 TextBox 对象的引用:

private static TextBox GetPrivateField(NumericUpDownEx ctrl)
{
    // find internal TextBox
    System.Reflection.FieldInfo textFieldInfo = typeof(NumericUpDown).GetField("upDownEdit", System.Reflection.BindingFlags.FlattenHierarchy | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
    // take some caution... they could change field name
    // in the future!
    if (textFieldInfo == null) {
        return null;
    } else {
        return textFieldInfo.GetValue(ctrl) as TextBox;
    }
}

干杯

于 2013-11-08T14:05:55.450 回答