有效性规则为WPF文本框 [英] ValidationRule for WPF Textbox
问题描述
我是新手,WPF.In我的用户,我有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的结尾。文字
应 xxxx.abc
, TextBox2.text
应xxxx.def等on.if文本框不应该有红色边框。
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.
希望我的details.So待办事项清楚我需要编写不同的有效性规则
每个文本框??
hope I am clear with the details.So Do i need to write different ValidationRule
for each textbox??
任何你输入??
推荐答案
为什么不能有一个有效性规则
执行情况,财产暴露哪些领域应,例如结尾:
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);
}
}
然后就可以用这个像这样
Then you can use this like so:
<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文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!