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 文本框的验证规则
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 使用 rss + c# 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
