当我使用numberseupdown设置为true的numbericupdown对象时,它只更新文本以在失去焦点时正确显示逗号。有没有办法在每次更改值时强制刷新它?
答案 0 :(得分:1)
你需要做一个活动。 众所周知,thounsandseperator是由焦点触发的,我们可以在输入时简单地调用它。
private void numericUpDown1_KeyUp(object sender, KeyEventArgs e)
{
numericUpDown1.Focus();
//Edit:
numericUpDown1.Select(desiredPosition,0)
}
因此,作为用户类型,我们给它重新关注的框,这是一个黑客,可以回忆千万个人的格式。
注意:黑客的问题是需要更多黑客的奇怪情况......例如:光标设置回文本的前面......你需要另一个黑客来修复它。
尝试其他事件以找到适合您案例的事件。
编辑:顺便说一下,如果你想进一步了解这个......
答案 1 :(得分:0)
要格式化控件中的文本值,您需要调用ParseEditText(),该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);
}
}