gpt4 book ai didi

c# - WPF 文本框的验证规则

转载 作者:太空狗 更新时间:2023-10-29 19:50:21 26 4
gpt4 key购买 nike

我是 WPF 的新手。在我的用户控件中,我有 8 个标签及其各自的 8 个文本框,如下所示:

1.Label : abc   2.Label : def
TextBox1 : TextBox2 :

3.Label :xyz 4. Label : ghi
Textbox3 : TextBox4 :

这些文本框文本属性中的每一个都应包含以其各自的标签名称结尾的文本对于 TextBox1.text 应该是 xxxx.abcTextBox2.text 应该是 xxxx.def 等等。如果不是文本框应该有红色边框.

希望我清楚细节。所以我需要为每个文本框编写不同的 ValidationRule 吗??

你有什么意见吗??

最佳答案

为什么没有一个 ValidationRule 实现,其中包含一个属性,该属性公开字段应该以什么结尾,例如:

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>

关于c# - WPF 文本框的验证规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14481240/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com