当我使用将千位分隔符设置为 true 的 numbericupdown 对象时,它只会在失去焦点时更新文本以正确显示逗号。有没有办法在每次更改值时强制刷新?
问问题
1519 次
2 回答
1
你需要做一个活动。众所周知,千分隔符是由焦点触发的,我们可以在键入时简单地调用它。
private void numericUpDown1_KeyUp(object sender, KeyEventArgs e)
{
numericUpDown1.Focus();
//Edit:
numericUpDown1.Select(desiredPosition,0)
}
因此,当用户键入时,我们将焦点返回给该框,这是一种召回千位分隔符格式的技巧。
注意:黑客问题是需要更多黑客的奇怪情况......例如:光标回到文本的前面......你需要另一个黑客来修复它。
尝试其他事件以找到适合您情况的事件。
编辑:顺便说一句,如果你真的想更进一步......
- 跟踪光标。
- 调用 keyup 时将光标放回正确的位置。 在 numericUpDown 控件中设置光标位置
于 2011-03-15T22:00:42.617 回答
0
要格式化控件中的文本值,您需要调用 ParseEditText(),它是受保护的,但可以从继承 NumericUpDown 的类中访问。问题是在您调用后光标将移动到第一个字符之前。为了控制光标的位置,您需要访问 NumericUpDown 不公开的 SelectionStart 属性。NumericUpDown 仍然有一个类型为 UpDownEdit 的名为 upDownEdit 的字段。UpDownEdit 类虽然内部继承自 TextBox 并且行为很像。所以一个解决方案是从 NumericUpDown 继承并使用反射来获取/设置 upDownEdit.SelectionStart 的值。这是您可以处理的事情:
public class NumericUpDownExt : NumericUpDown
{
private static FieldInfo upDownEditField;
private static PropertyInfo selectionStartProperty;
private static PropertyInfo selectionLengthProperty;
static NumericUpDownExt()
{
upDownEditField = (typeof(UpDownBase)).GetField("upDownEdit", BindingFlags.Instance | BindingFlags.NonPublic);
Type upDownEditType = upDownEditField.FieldType;
selectionStartProperty = upDownEditType.GetProperty("SelectionStart");
selectionLengthProperty = upDownEditType.GetProperty("SelectionLength");
}
public NumericUpDownExt() : base()
{
}
public int SelectionStart
{
get
{
return Convert.ToInt32(selectionStartProperty.GetValue(upDownEditField.GetValue(this), null));
}
set
{
if (value >= 0)
{
selectionStartProperty.SetValue(upDownEditField.GetValue(this), value, null);
}
}
}
public int SelectionLength
{
get
{
return Convert.ToInt32(selectionLengthProperty.GetValue(upDownEditField.GetValue(this), null));
}
set
{
selectionLengthProperty.SetValue(upDownEditField.GetValue(this), value, null);
}
}
protected override void OnTextChanged(EventArgs e)
{
int pos = SelectionStart;
string textBefore = this.Text;
ParseEditText();
string textAfter = this.Text;
pos += textAfter.Length - textBefore.Length;
SelectionStart = pos;
base.OnTextChanged(e);
}
}
于 2011-03-17T13:53:34.293 回答