WPF/XAML:在代码和标记中应用时 ExceptionValidationRule 不同吗?
我遇到过需要将 ExceptionValidationRule 应用到 WPF 表单上的许多文本框的情况。我可以使用标记来做到这一点,并且得到所需的结果(当输入无效值时,文本框会显示红色轮廓),但只有当我在标记中提供规则时:
<TextBox x:Name="Name" Width="150" >
<TextBox.Text>
<Binding Path="Name" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" NotifyOnValidationError="True">
<Binding.ValidationRules>
<ExceptionValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
但是当我使用代码应用值时:
Name.GetBindingExpression(TextBox.TextProperty).ParentBinding.ValidationRules.Add(new ExceptionValidationRule());
我没有得到期望的结果。此代码在 InitalizeComponent() 调用之后应用到 userControl 的构造函数中。用户控件具有文本框“名称”作为子控件。
我已经完成了,我可以看到,当使用两者时,两个验证规则被放入 ValidationRules 集合中,但是当我仅使用代码版本时,当输入了无效值。
我是否只是误解了 WPF 的基本规则?
或者,有没有办法可以使用样式应用此验证规则?说实话,我更愿意这样。
谢谢, 中号
I've run across the need to apply the ExceptionValidationRule to many textboxes on a form in WPF. I can do this with markup and I get the desired result (the textbox gets a red outline when an invalid value is entered) but only when I supply the rule in markup:
<TextBox x:Name="Name" Width="150" >
<TextBox.Text>
<Binding Path="Name" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" NotifyOnValidationError="True">
<Binding.ValidationRules>
<ExceptionValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
But when I apply the value using code:
Name.GetBindingExpression(TextBox.TextProperty).ParentBinding.ValidationRules.Add(new ExceptionValidationRule());
I don't get the desired results. This code is applied in a userControl's constructor after the InitalizeComponent() call. The user control has the textbox "Name" as a child control.
I've gone through and I can see, when using both, that two validation rules are put in the ValidationRules collection but when I am using just the code version I don't get the desired result of a red outline around the textbox when an invalid value is entered.
Am I just misunderstanding a fundamental rule to WPF?
Or, is there a way I can apply this validation rule using a Style? I'd prefer that, to tell you the truth.
Thanks,
M
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Binding 在使用后就无法更改,显然这也适用于 ValidationRules。您可以在代码中创建一个新的绑定,但这可能不是您想要的。
由于 Binding 或 ValidationRule 不是从 FrameworkElement 派生的,因此 Style 也不起作用。在您的情况下,我要做的是一个子类化的绑定,您可以在其中添加您需要的所有内容。像这样的
ExBinding,添加 ValidationRule 等。
You can't change a Binding after it has been used, and apperently that goes for the ValidationRules as well. You can create a new Binding in code but that's probably not what you're after.
A Style won't work either since a Binding or ValidationRule doesn't derive from FrameworkElement. What I would do in your situation is a subclassed Binding where you add all the things you need. Something like this
The ExBinding, adding ValidationRule etc.