[英]How to force textbox to take only numbers in WPF?
我希望用戶只在TextBox
輸入數值。
我得到了這段代碼:
private void txtType1_KeyPress(object sender, KeyPressEventArgs e)
{
int isNumber = 0;
e.Handled = !int.TryParse(e.KeyChar.ToString(), out isNumber);
}
但是在使用WPF時我沒有得到textbox_KeyPress
事件和e.KeyChar
。
什么是WPF的解決方案?
Edit:
我做了一個解決方案!
private void txtName_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
CheckIsNumeric(e);
}
private void CheckIsNumeric(TextCompositionEventArgs e)
{
int result;
if(!(int.TryParse(e.Text, out result) || e.Text == "."))
{
e.Handled = true;
}
}
protected override void OnPreviewTextInput(TextCompositionEventArgs e)
{
char c = Convert.ToChar(e.Text);
if (Char.IsNumber(c))
e.Handled = false;
else
e.Handled = true;
base.OnPreviewTextInput(e);
}
您可以使用驗證規則... http://www.codeproject.com/KB/WPF/wpfvalidation.aspx
或制作自己的Maskable文本框http://rubenhak.com/?p=8
您可以使用依賴項屬性和內部依賴項屬性的驗證方法綁定文本框,您可以檢查int.tryparse是否返回true,否則您可以使用默認值,也可以重置值。
或者,您可以使用WPF ValidationRules找出值的更改時間。 一旦更改,您可以應用inout validaiton的邏輯。
或者您可以使用IDataError Info進行驗證。
在WPF中,鍵碼值與正常的winforms e.keychar值不同,
在文本框的PreviewKeyDown事件中,添加以下代碼:
if ((e.key < 34) | (e.key > 43)) {
if ((e.key < 74) | (e.key > 83)) {
if ((e.key == 2)) {
return;
}
e.handled = true;
}
}
這將允許用戶只輸入Numpad0 - Numpad9部分中的Numbers和D0 - D9以及key.Back
希望這有助於,歡呼!
Hasib Uz Zaman的位增強版
private void txtExpecedProfit_PreviewTextInput_1(object sender, TextCompositionEventArgs e)
{
CheckIsNumeric((TextBox)sender,e);
}
private void CheckIsNumeric(TextBox sender,TextCompositionEventArgs e)
{
decimal result;
bool dot = sender.Text.IndexOf(".") < 0 && e.Text.Equals(".") && sender.Text.Length>0;
if (!(Decimal.TryParse(e.Text, out result ) || dot ) )
{
e.Handled = true;
}
}
這將檢查重復。(十進制標記)並且不會僅允許。(十進制標記)
//Call this code on KeyDown Event
if((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || (e.Key == Key.Back))
{ e.Handled = false; }
else if((e.Key >= Key.D0 && e.Key <= Key.D9))
{ e.Handled = false; }
else
{ e.Handled = true; }
private void shomaretextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
// xaml.cs code
if (!char.IsDigit(e.Text, e.Text.Length - 1))
e.Handled = true;
}
在xaml
<TextBox x:Name="shomaretextBox"
HorizontalAlignment="Left"
Height="28"
Margin="125,10,0,0"
TextWrapping="Wrap"
VerticalAlignment="Top"
Width="151"
Grid.Column="1"
TextCompositionManager.PreviewTextInput="shomaretextBox_PreviewTextInput" />
我相信你正在尋找的是PreviewTextInput
事件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.