简体   繁体   English

WPF验证和CanExecute命令

[英]WPF validation and CanExecute command

I'm trying to get the essence of my last question and bring some more clarity to the description. 我试图弄清我最后一个问题的本质,并使描述更加清晰。

Given is an WPF form to submit new data with two textfields and a "Save" button. 给出了一个WPF表单,用于通过两个文本字段和一个“保存”按钮提交新数据。 Both textfields are required fields and are bound to ViewModel properties. 这两个文本字段都是必填字段,并且绑定到ViewModel属性。 Button is bound to "Execute" relay command with Execute and CanExecute methods. 按钮通过Execute和CanExecute方法绑定到“ Execute”中继命令。 CanExecute returns !HasErrors of the ViewModel. CanExecute返回ViewModel的!HasErrors。 ViewModel implements INotifyPropertyChanged and INotifyDataErrorInfo interfaces. ViewModel实现INotifyPropertyChanged和INotifyDataErrorInfo接口。 Property setter runs the validation for this property only. 属性设置器仅对此属性运行验证。

The goals are: 目标是:

  • Disable the "Save" button initially. 首先禁用“保存”按钮。
  • Enable the "Save" button only if both textfields are validated successfully without validation of the whole ViewModel on every property change. 仅在两个文本字段都成功验证但每次属性更改都不验证整个ViewModel的情况下,才启用“保存”按钮。

For the first goal I use the isValidated bool property which is initially false and become true as soon as first validation occurred. 对于第一个目标,我使用isValidated bool属性,该属性最初为false,并在首次验证发生后立即变为true。 This property is then checked together with HasErros in the CanExecute method. 然后在CanExecute方法中将该属性与HasErros一起检查。 Is there a more elegant way? 有没有更优雅的方式?

I have no idea how to implement the second goal. 我不知道如何实现第二个目标。 Any thought on this? 有什么想法吗?

THX 谢谢

Your two goals are only one goal really. 您的两个目标实际上只是一个目标。 Let's look at your second goal first: 让我们先来看第二个目标:

• Enable the "Save" button only if both textfields are validated successfully without validation of the whole ViewModel on every property change. •仅在两个文本字段都成功验证但未对每个属性更改进行整个ViewModel验证的情况下,才启用“保存”按钮。

Initially, your text fields will be empty, so presumably, they will not pass validation. 最初,您的文本字段将为空,因此大概不会通过验证。 Therefore initially, your Save Button will be disabled, as per your first goal: 因此,根据您的第一个目标,最初,您的“ Save Button 被禁用:

• Disable the "Save" button initially. •首先禁用“保存”按钮。

Secondly, in your last question (which you should probably add a link to if you're going to mention it in this post), you had some problem with using !HasErros in the CanExecute handler. 其次,在您的最后一个问题中(如果要在本文中提及,您可能应该添加一个链接),您在CanExecute处理程序中使用!HasErros遇到了一些问题。 This time, you do need to validate all of the properties together to fulfil your second requirement... so just use !HasErros in the CanExecute handler. 这次,您确实需要一起验证所有属性才能满足您的第二个要求……因此只需在CanExecute处理程序中使用!HasErros

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

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