C# 文本框验证未按预期工作
我在WPF中的文本框上实现数字验证程序时遇到问题。如果用户在文本框中输入类似abc的内容,则会弹出警告/错误消息。如果他们输入1.99,就可以了。据我所知,目前正在发生的是,验证没有被触发。另一个问题是,在页面加载时,我将文本框的值设置为预定义值,但当您看到页面加载时,文本框为空。因此,文本框中没有出现类似13.42的内容,而是空白。但是,当我删除C# 文本框验证未按预期工作,c#,regex,wpf,C#,Regex,Wpf,我在WPF中的文本框上实现数字验证程序时遇到问题。如果用户在文本框中输入类似abc的内容,则会弹出警告/错误消息。如果他们输入1.99,就可以了。据我所知,目前正在发生的是,验证没有被触发。另一个问题是,在页面加载时,我将文本框的值设置为预定义值,但当您看到页面加载时,文本框为空。因此,文本框中没有出现类似13.42的内容,而是空白。但是,当我删除部分时,会显示该值 下面是我的正则表达式验证程序类: public class RegexValidation : ValidationRule
部分时,会显示该值
下面是我的正则表达式验证程序类:
public class RegexValidation : ValidationRule
{
private string pattern;
private Regex regex;
public string Expression
{
get { return pattern; }
set
{
pattern = value;
regex = new Regex(pattern, RegexOptions.IgnoreCase);
}
}
public RegexValidation() { }
public override ValidationResult Validate(object value, CultureInfo ultureInfo)
{
if (value == null || !regex.Match(value.ToString()).Success)
{
return new ValidationResult(false, "The value is not a valid number");
}
else
{
return new ValidationResult(true, null);
}
}
}
下面是我的页面资源:
<Page.Resources>
<system:String x:Key="regexDouble">^\d+(\.\d{1,2})?$</system:String>
<ControlTemplate x:Key="TextBoxErrorTemplate">
<StackPanel>
<StackPanel Orientation="Horizontal">
<AdornedElementPlaceholder x:Name="Holder"/>
</StackPanel>
<Label Foreground="Red" Content="{Binding ElementName=Holder, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"/>
</StackPanel>
</ControlTemplate>
</Page.Resources>
修复了我的问题,验证程序按预期工作。问题在于我是如何约束的。我试图在代码隐藏中设置每个文本框的文本,而不是使用绑定路径。一旦我从使用
txtextbox.Text=“123”
切换到以下操作,一切都正常,并开始正常工作
private void fillInventoryInformation(Inventory i)
{
DataContext = i;
}
嘿,你们应该准备好验证函数。然后在文本框更改事件中调用它。所以只要你在上面打字,它就会运行。当用户键入可接受的字符时,它将显示您定义的错误消息。如果您有时间,请提供一个如何执行此操作的链接?我会帮你的,我会调查的。谢谢您,而不是使用
!regex.Match(value.ToString()).Success
试试!regex.IsMatch(value.ToString())
它是为验证而设计的。
private string price;
public string intPrice
{
get { return price; }
set { price = value; }
}
private void fillInventoryInformation(Inventory i)
{
//This method is called from the starter method on this page.
//Here I am setting the value of intPrice
intPrice= (Convert.ToDouble(i.intPrice) / 100).ToString();
//This was how I was previously trying to set the value of the textbox
txtItemPrice.Text = (Convert.ToDouble(i.intPrice) / 100).ToString();
}
private void fillInventoryInformation(Inventory i)
{
DataContext = i;
}