C# WinRT アプリでフォームを作成していますが、TextBox コンポーネントの 1 つの文字を数字のみに制限したいと考えています。(この TextBox は、ユーザーが年を入力するためのものです。)
しばらく検索しましたが、イベントにイベントリスナーを設定し、キーを押すたびにプロパティTextChanged
を検査しないと、これを理解できませんでした。text
ユーザーが特定の文字のみを TextBox に入力できると簡単に言う方法はありますか?
C# WinRT アプリでフォームを作成していますが、TextBox コンポーネントの 1 つの文字を数字のみに制限したいと考えています。(この TextBox は、ユーザーが年を入力するためのものです。)
しばらく検索しましたが、イベントにイベントリスナーを設定し、キーを押すたびにプロパティTextChanged
を検査しないと、これを理解できませんでした。text
ユーザーが特定の文字のみを TextBox に入力できると簡単に言う方法はありますか?
おそらく機能する可能性のある最も簡単なことは、OnTextChanged
イベントにバインドし、ルールに従ってテキストを変更することです。
<TextBox x:Name="TheText" TextChanged="OnTextChanged" MaxLength="4"/>
private void OnTextChanged(object sender, TextChangedEventArgs e)
{
if (TheText.Text.Length == 0) return;
var text = TheText.Text;
int result;
var isValid = int.TryParse(text, out result);
if (isValid) return;
TheText.Text = text.Remove(text.Length - 1);
TheText.SelectionStart = text.Length;
}
ただし、MetroのマントラはタッチファーストUIであり、コントロールを使用してタッチファーストの方法で簡単に実行できるため、このアプローチは避けたいと思いますFlipView
。
リンクでの投稿に基づいて、ナビゲーションを可能にするタブを追加します。
private void decimalTextBox_KeyDown(object sender, KeyRoutedEventArgs e)
{
bool isGoodData; // flag to make the flow clearer.
TextBox theTextBox = (TextBox)sender; // the sender is a textbox
if (e.Key>= Windows.System.VirtualKey.Number0 && e.Key <= Windows.System.VirtualKey.Number9) // allow digits
isGoodData = true;
else if (e.Key == Windows.System.VirtualKey.Tab)
isGoodData = true;
else if (e.Key >= Windows.System.VirtualKey.NumberPad0 && e.Key <= Windows.System.VirtualKey.NumberPad9) // allow digits
isGoodData = true;
else if (e.Key == Windows.System.VirtualKey.Decimal || (int)e.Key == 190) // character is a decimal point, 190 is the keyboard period code
// which is not in the VirtualKey enumeration
{
if (theTextBox.Text.Contains(".")) // search for a current point
isGoodData = false; // only 1 decimal point allowed
else
isGoodData = true; // this is the only one.
}
else if (e.Key == Windows.System.VirtualKey.Back) // allow backspace
isGoodData = true;
else
isGoodData = false; // everything else is bad
if (!isGoodData) // mark bad data as handled
e.Handled = true;
}
これは私にとってはうまくいくようです:
private void TextBox_KeyDown(object sender, KeyRoutedEventArgs e)
{
if ((e.Key < VirtualKey.Number0) || (e.Key > VirtualKey.Number9))
{
// If it's not a numeric character, prevent the TextBox from handling the keystroke
e.Handled = true;
}
}
すべての値については、 VirtualKey列挙のドキュメントを参照してください。