ValidationRule for WPF Textbox(WPF 文本框的验证规则)
问题描述
我是 WPF 的新手.在我的 UserControl 中,我有 8 个标签及其各自的 8 个文本框,如下所示:
I am newbie to WPF.In my UserControl,I have 8 labels and its respective 8 textboxes as follows:
1.Label : abc 2.Label : def
TextBox1 : TextBox2 :
3.Label :xyz 4. Label : ghi
Textbox3 : TextBox4 :
每个文本框文本属性都应包含以其各自标签名称结尾的文本对于 TextBox1.text
应该是 xxxx.abc
,TextBox2.text
应该是 xxxx.def 等等.如果不是,文本框应该有红色边框.
Each of these textbox text property should contain text ending with its respective label name
for TextBox1.text
should be xxxx.abc
, TextBox2.text
should be xxxx.def and so on.if not textbox should have red border.
希望我对细节很清楚.所以我需要为每个文本框编写不同的 ValidationRule
吗??
hope I am clear with the details.So Do i need to write different ValidationRule
for each textbox??
你有什么意见吗??
推荐答案
为什么不拥有一个 ValidationRule
实现,用一个属性公开字段应该以什么结尾,例如:
Why not have one ValidationRule
implementation, with a property exposing what the field should end with, e.g:
public class EndsWithValidationRule : ValidationRule
{
public string MustEndWith { get; set; }
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
var str = value as string;
if(str == null)
{
return new ValidationResult(false, "Please enter some text");
}
if(!str.EndsWith(MustEndWith))
{
return new ValidationResult(false, String.Format("Text must end with '{0}'", MustEndWith));
}
return new ValidationResult(true, null);
}
}
然后你可以这样使用:
<TextBox x:Name="TextBox1">
<TextBox.Text>
<Binding Path="BoundProperty1" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<local:EndsWithValidationRule MustEndWith=".def" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
<TextBox x:Name="TextBox2">
<TextBox.Text>
<Binding Path="BoundProperty2" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<local:EndsWithValidationRule MustEndWith=".abc" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
这篇关于WPF 文本框的验证规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:WPF 文本框的验证规则
基础教程推荐
- SSE 浮点算术是否可重现? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 XML 转换为通用列表 2022-01-01