[英]TextBox in WPF and text format
我試圖創建一個TextBox控件,並強迫用戶僅在此處輸入特定格式的數字。
我如何在WPF中做到這一點?
我在TextBox類中未找到任何屬性,例如“ TextFormat”或“ Format”。
我這樣制作了TextBox(不在可視編輯器中):
TextBox textBox = new TextBox();
我想要TextBox行為像在MS Access表單中一樣(例如,用戶只能在該文本框中以“ 000.0”格式放置數字)。
考慮使用WPF的內置驗證技術。 請參閱有關ValidationRule
類的此MSDN文檔以及此方法文檔。
您可能需要的是屏蔽輸入。 WPF沒有一個,因此您可以自己實現(例如,通過使用validate ),也可以使用可用的第三方控件之一:
根據您的澄清,您希望將用戶輸入限制為帶小數點的數字。 您還提到過您正在以編程方式創建TextBox。
使用TextBox.PreviewTextInput事件確定字符的類型並驗證TextBox中的字符串,然后在適當的地方使用e.Handled取消用戶輸入。
這將達到目的:
public MainWindow()
{
InitializeComponent();
TextBox textBox = new TextBox();
textBox.PreviewTextInput += TextBox_PreviewTextInput;
this.SomeCanvas.Children.Add(textBox);
}
進行驗證的肉類和土豆類:
void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
// change this for more decimal places after the period
const int maxDecimalLength = 2;
// Let's first make sure the new letter is not illegal
char newChar = char.Parse(e.Text);
if (newChar != '.' && !Char.IsNumber(newChar))
{
e.Handled = true;
return;
}
// combine TextBox current Text with the new character being added
// and split by the period
string text = (sender as TextBox).Text + e.Text;
string[] textParts = text.Split(new char[] { '.' });
// If more than one period, the number is invalid
if (textParts.Length > 2) e.Handled = true;
// validate if period has more than two digits after it
if (textParts.Length == 2 && textParts[1].Length > maxDecimalLength) e.Handled = true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.