WinForms NumericUpDown:有没有办法读取有关文本选择的信息?
WinForms NumericUpDown允许我们使用select(Int32,Int32)方法选择其中的文本范围。是否有任何方法可以设置/检索所选文本的起始点、所选字符数和所选文本部分,就像我们可以使用SelectionStart、SelectionLength和SelectedText属性为其他类似文本框的控件设置/检索一样?这在vanilla NumericUpDown控件中是不可能的 在本文中,作者解释了如何将NumericUpDown控件子类化以公开底层TextBox对象,从而公开“缺失”属性:WinForms NumericUpDown:有没有办法读取有关文本选择的信息?,winforms,selection,textselection,numericupdown,Winforms,Selection,Textselection,Numericupdown,WinForms NumericUpDown允许我们使用select(Int32,Int32)方法选择其中的文本范围。是否有任何方法可以设置/检索所选文本的起始点、所选字符数和所选文本部分,就像我们可以使用SelectionStart、SelectionLength和SelectedText属性为其他类似文本框的控件设置/检索一样?这在vanilla 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; }
}
}
他使用反射获取对底层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;
}
}
CheersNumericUpDown控件有一个可从控件集合访问的内部文本框。它是集合中继UpDownButtons控件之后的第二个控件。由于WinForms不再处于开发阶段,因此可以说NumericUpDown控件的底层架构不会改变 通过从NumericUpDown控件继承,可以轻松公开这些文本框属性:
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; }
}
}
与LarsTech的回答类似,您可以快速将
NumericUpDown.Controls[1]
转换为TextBox
来访问这些属性,而无需创建新类
((TextBox)numericUpDown1.Controls[1]).SelectionLength; // int
((TextBox)numericUpDown1.Controls[1]).SelectionStart; // int
((TextBox)numericUpDown1.Controls[1]).SelectedText; // string
那是个好主意!!我知道NumericUpDown由几个子控件组成,其中一个是TextBox,所以实际上所有解决方案的关键是如何找到这个文本框。但是我想这种方法是最简单的,而且它也不使用反射,这可能会导致安全限制问题。如果我们担心子控件索引1,我们可以简单地枚举NumericUpDown.Controls集合并找到TextBox类型的控件,以使代码健壮且通用。