在 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)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您已经在 ViewModel 上实现了
IDataErrorInfo
,我发现此数据模板对于显示错误非常有用:这样,您只需将
ValidatesOnDataErrors=True
设置为您的文本框绑定,如果有任何问题,您会收到一个显示错误的工具提示。这也可以应用于其他控件。有关如何正确实现 IDataErrorInfo 的信息,请参见此处:
http://blogs .msdn.com/b/wpfsdk/archive/2007/10/02/data-validation-in-3-5.aspx
特别是看看“3.5 IDataErrorInfo Support”部分
If you already have implemented
IDataErrorInfo
on your ViewModels, I found this data-template to be quite useful for displaying errors: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"
我最近不得不处理这个问题,所以我将发布这个示例代码来帮助其他人解决同样的问题。
此样式应适用于 WPF Xceed.PropertyGrid 和 WPF PropertyTools.PropertyGrid。
I recently had to deal with this problem so I will post this example code to help others with the same problem.
This style should work on WPF Xceed.PropertyGrid and WPF PropertyTools.PropertyGrid.
我建议使用
IDataErrorInfo
。这样,验证逻辑将保持附加到ViewModel
而不是UI
。WPF
也对其提供了很好的支持。I recommend using
IDataErrorInfo
. That way, validation logic stays attached toViewModel
and not theUI
. AndWPF
has well support for it as well.