简体   繁体   English

使用Model View Presenter(MVP)验证UI控件

[英]Validate UI Control with Model View Presenter (MVP)

I have been using winforms for many years. 我已经使用winform多年了。 Normally I write a form and that form, in the code behind does everything (validates user input, communicates with the database…). 通常,我编写一个表单,然后该表单在后面的代码中执行所有操作(验证用户输入,与数据库进行通信……)。 Recently a friend introduced me to MVP and I have been trying to learn to use it. 最近,一个朋友向我介绍了MVP,我一直在尝试学习使用它。 The problem I am having is replicated some of the stuff I used to be able to do with the form. 我遇到的问题是复制了我以前可以处理表单的一些内容。 For example, in the past if I had a textbox and the user entered something invalid in the textbox, I could turn that textbox red, set focus on the textbox and alert the user that they entered something invalid in that testbox. 例如,过去,如果我有一个文本框,并且用户在文本框中输入了无效的内容,则可以将该文本框设为红色,将焦点放在文本框上,并警告用户他们在该测试框中输入了无效的内容。 With my validation now being done in the presenter or model layer, I can Messagebox the user that something is not valid but how can I setfocus to a control or change a controls color? 现在,我已经在演示者或模型层中完成了验证,我可以向Messagebox用户发送一些无效信息,但是如何将焦点设置为控件或更改控件颜色?

Your presenter holds a reference to the view anyway, so you can just manipulate the widgets (text boxes etc.) directly from the presenter. 演示者仍然拥有对该视图的引用,因此您可以直接从演示者操作小部件(文本框等)。 Or, possibly better, have a method in the view like nameIsInvalid() , where you write your desired behaviour (changing color, setting focus). 或者,可能更好的方法是在视图中有一个类似nameIsInvalid() ,您可以在其中编写所需的行为(更改颜色,设置焦点)。 This method is called when the presenter notices that the input validation has failed. 当演示者注意到输入验证失败时,将调用此方法。

The validation itself should be done in the model, since that is view-independent. 验证本身应在模型中完成,因为这与视图无关。

As always, you don't need to be super dogmatic about that. 像往常一样,您不必对此格格不入。 If it makes sense to have some simple validation associated directly with the widget, then leave it there. 如果让一些简单的验证直接与该窗口小部件有意义,则将其保留在那里。 But a final validation of the whole form should be handled as I've described above. 但是,如上所述,应该对整个表单进行最终验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM