数千区切りを true に設定して numbericupdown オブジェクトを使用すると、テキストが更新され、フォーカスが失われたときにのみコンマが正しく表示されます。値が変更されるたびに強制的に更新する方法はありますか?
2 に答える
イベントを行う必要があります。ご存知のように、入力時に単純に呼び出すことができる focus によって、thunsandseperator がトリガーされます。
private void numericUpDown1_KeyUp(object sender, KeyEventArgs e)
{
numericUpDown1.Focus();
//Edit:
numericUpDown1.Select(desiredPosition,0)
}
そのため、ユーザー タイプとして、ボックスにフォーカスを戻します。これは、3 桁区切りの書式設定を思い出すためのハックです。
注: ハッキングの問題は、より多くのハックを必要とする奇妙な状況です... 例: カーソルがテキストの先頭に戻る... 修正するには別のハックが必要です。
他のイベントを試して、自分のケースに合ったものを見つけてください。
編集:ところで、これをさらに進めたい場合は...
- カーソルを追跡します。
- keyup が呼び出されたときに、カーソルを正しい位置に戻します。 numericUpDown コントロールでのカーソル位置の設定
コントロールのテキスト値をフォーマットするには、ParseEditText() を呼び出す必要があります。これは保護されていますが、NumericUpDown を継承するクラスからアクセスできます。問題は、呼び出し後にカーソルが最初の文字の前に移動することです。カーソルの位置を制御するには、NumericUpDown が公開していない SelectionStart プロパティにアクセスする必要があります。NumericUpDown には、タイプ UpDownEdit の upDownEdit という名前のフィールドがまだあります。UpDownEdit クラスは、Internal が 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);
}
}