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 文本框的验证规则
基础教程推荐
- 将数据集转换为列表 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 从 C# 控制相机设备 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 如果条件可以为空 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
