C# 仅允许数字和句点的文本框
我对C#和WPF还比较陌生,但我正在尝试创建一个最多只允许14个数字和3个句点的文本框,以及另一个只允许5个数字的文本框。我该怎么做?我研究过stackoverflow,但不知什么原因,运气不好。我尝试过许多“解决方案”,但这些方案对我来说都不起作用。如果您愿意,可以这样设置绑定:C# 仅允许数字和句点的文本框,c#,.net,wpf,regex,visual-studio-2012,C#,.net,Wpf,Regex,Visual Studio 2012,我对C#和WPF还比较陌生,但我正在尝试创建一个最多只允许14个数字和3个句点的文本框,以及另一个只允许5个数字的文本框。我该怎么做?我研究过stackoverflow,但不知什么原因,运气不好。我尝试过许多“解决方案”,但这些方案对我来说都不起作用。如果您愿意,可以这样设置绑定: <TextBox Text="{Binding Field, UpdateSourceTrigger=PropertyChanged}" /> 我在看nakiya的解决方案,我可以看出你不知道该怎么做。
<TextBox Text="{Binding Field, UpdateSourceTrigger=PropertyChanged}" />
我在看nakiya的解决方案,我可以看出你不知道该怎么做。我会举一个完整的例子,这样你可以从中学到一些东西。看一看: MainWindow.xaml
MainWindow.cs
private void TextBoxBase\u OnTextChanged(对象发送方,textchangedventargs e){
var textBox=发送方作为textBox;
如果(文本框!=null){
字符串newValue=textBox.Text;
int changed=ValidateText(ref newValue);
int-selectionStart=textBox.selectionStart;
Text=newValue;
textBox.SelectionStart=SelectionStart-已更改;
}
}
私有int ValidateText(参考字符串输入){
//如果没有值,则返回空字符串
if(input==null)返回0;
int=0;
//检查输入字符串并创建只包含数字和句点的新字符串
StringBuilder=新的StringBuilder();
for(int index=0;index
我已编辑了您的标题。请看,“,其中的共识是“不,他们不应该”。哎呀,对不起!您可能正在寻找一个蒙面文本框。看看这是否有帮助:可能有帮助。问题是我正在使用MahApps.Metro并使用文本框控件。我不知道这是否行得通。“MakeNumeric”,“_字段”不存在。无法从字符串转换为System.Windows.DependencyPropertyChangedEventArgs。与“System.Windows.DependencyObject.OnPropertyChanged(System.Windows.DependencyPropertyChangedEventArgs)”匹配的最佳重载方法有一些无效参数。这是我不理解的。我是C#的新手,所以我不太确定这里的情况如何/@RBLXDev:您必须根据需要实现MakeNumeric
方法。您还希望在拥有字段的类中实现INotifyPropertyChanged
。但是如何实现呢?我不明白如何实现MakeNumeric。引用《偷盗者》中的一句话:“你必须创建一个私有字符串MakeNumeric(string valueToCheck)方法,然后在该方法中放入你需要的任何验证。”谢谢!我不懂一半的代码,MSDN时间!
public string Field
{
get { return _field; }
set
{
var val = MakeNumeric(value)
_field = value;
OnPropertyChanged("Field");
}
}
<TextBox TextChanged="TextBoxBase_OnTextChanged" />
private void TextBoxBase_OnTextChanged(object sender, TextChangedEventArgs e) {
var textBox = sender as TextBox;
if (textBox != null) {
string newValue = textBox.Text;
int changed = ValidateText(ref newValue);
int selectionStart = textBox.SelectionStart;
textBox.Text = newValue;
textBox.SelectionStart = selectionStart - changed;
}
}
private int ValidateText(ref string input) {
// If no value, return empty string
if (input == null) return 0;
int changed = 0;
// Go through input string and create new string that only contains digits and period
StringBuilder builder = new StringBuilder();
for (int index = 0; index < input.Length; index++) {
if (Char.IsDigit(input[index]) || input[index] == '.')
builder.Append(input[index]);
else changed++;
}
input = builder.ToString();
return changed;
}