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 文本框的验证规则
基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
