我有我想有兩種方式來限制一個文本框:好奇的錯誤與TextChanged事件(WPF文本框)
1 - 我只希望允許數值,沒有小數
2 - 我只希望接受包含數字< = 35
我有以下的事件來處理這個問題:
private void TextBoxWorkflowCountPreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (!IsNumeric(e.Text, NumberStyles.Integer)) e.Handled = true;
}
public bool IsNumeric(string val, NumberStyles numberStyle)
{
double result;
return double.TryParse(val, numberStyle, CultureInfo.CurrentCulture, out result);
}
private void TextBoxWorkflowCountTextChanged(object sender, TextChangedEventArgs e)
{
if (!string.IsNullOrEmpty(textBoxWorkflowCount.Text) && Convert.ToInt32(textBoxWorkflowCount.Text) <= 35) e.Handled = true;
else
{
MessageBox.Show("Must not be higher then 35");
textBoxWorkflowCount.Text = "35";
}
}
這表面上的工作完全正常 - 除了用戶將數據粘貼到文本框(不可避免)或者更好奇時使用時,如果用戶輸入一個數字然後點擊退格(使文本框再次變爲空白),則讓用戶知道其值> 35出現(儘管情況絕非如此)。如果必須的話,我可以忍受的第一個問題 - 但第二個問題是遊戲突破,並且在嘗試解決問題30分鐘後我無處可去。幫幫我!
哇,這是輝煌的 - 一定會用的。謝謝! – Codingo 2012-08-11 19:01:10