在WPF PropertyGrid中实现验证(Implementing validations in WPF PropertyGrid)

编程入门 行业动态 更新时间:2024-10-26 08:32:25
在WPF PropertyGrid中实现验证(Implementing validations in WPF PropertyGrid)

我已经实现了一个PropertyGrid并且在其中显示了所选对象(在另一个库中)的属性。 属性值通过绑定绑定到PropertyGrid控件。 现在,我想对用户在PropertyGrid控件(主要是TextBox )中输入的值执行验证,并在值不正确时向用户显示消息。

将会有一些常见的验证,如数值,必填字段等,以及一些与业务逻辑相关的验证(如值不能超过此等)。

所有可用的方法都可以实现( IDataErrorInfo或其他)?

I have implemented a PropertyGrid and properties of selected object(in another library) are displayed in it. Property values are bound to PropertyGrid controls through binding. Now, I want to perform validation on values user enters in PropertyGrid control(mainly TextBox) and display a message to user if value is not correct.

There will be some common validations like numeric values, required field etc and some business logic related validations(like value can't be more then this etc.).

What all approaches are available to implement this(IDataErrorInfo or something else)?

最满意答案

如果您已经在ViewModel上实现了IDataErrorInfo ,我发现这个数据模板对于显示错误非常有用:

<Style TargetType="{x:Type TextBox}"> <Style.Triggers> <Trigger Property="Validation.HasError" Value="true"> <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" /> </Trigger> </Style.Triggers> </Style>

这样,您只需要在文本框绑定上设置ValidatesOnDataErrors=True ,如果出现任何错误,您将获得显示错误的工具提示。 这也可以应用于其他控件。

有关如何正确实现IDataErrorInfo的信息,请在此处查看: http://blogs.msdn.com/b/wpfsdk/archive/2007/10/02/data-validation-in-3-5.aspx 特别看看“ 3.5 IDataErrorInfo支持 ”部分

If you already have implemented IDataErrorInfo on your ViewModels, I found this data-template to be quite useful for displaying errors:

<Style TargetType="{x:Type TextBox}"> <Style.Triggers> <Trigger Property="Validation.HasError" Value="true"> <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" /> </Trigger> </Style.Triggers> </Style>

That way, you only have to set ValidatesOnDataErrors=True on your textbox bindings and you get a tooltip displaying the error if anything is wrong. That can be applied to other controls as well.

For information on how to implement IDataErrorInfo properly, look here: http://blogs.msdn.com/b/wpfsdk/archive/2007/10/02/data-validation-in-3-5.aspx especially have a look at the section "3.5 IDataErrorInfo Support"

更多推荐

PropertyGrid,values,验证,user,电脑培训,计算机培训,IT培训"/> <meta name="d

本文发布于:2023-07-28 23:30:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1310168.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:PropertyGrid   WPF   validations   Implementing

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!