我应该如何从 ViewModel 触发警报?
我向一些我认为具有良好设计意识的同事提出了这个问题。有趣的是,我收到了不同的回应。那么您认为哪个选项最适合 MVVM 模式,为什么?
假设我需要在 $ 大于 $10k 时显示警报图标。
- 选项 1:VM 具有属性“Amount”,XAML 触发器和/或绑定设置元素可见性
- 选项 2:VM 具有属性“ShowAlert”,XAML 使用 bool 到可见性转换器绑定可见性
- 选项 3:VM 具有属性“AlertVisibility”,XAML 绑定直接
- 选项4:其他(请说明)
感谢反馈!
I've asked this question of a few colleagues who I believe have good design sense. Interestingly, I've received varying responses. So which option do you think best fits the MVVM pattern and why?
Say I have a requirement to show an alert icon when $ greater than $10k.
- Option 1: VM has property "Amount", XAML trigger and/or binding sets element visibility
- Option 2: VM has property "ShowAlert", XAML binds visibility using a bool to visibility converter
- Option 3: VM has property "AlertVisibility", XAML binds directly
- Option 4: Other (please explain)
Thanks for the feedback!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您的情况下,您有明确的业务规则
Shown WHEN > 10k
,它应该封装在 ViewModel 而不是 View 中,因为 View 知道数据将如何显示,而不是何时和为何显示。因此,我建议公开
Amount
和ShowAlert
属性,并避免公开AlertVisibility
属性,因为它会分散诸如 可见性枚举状态(隐藏、折叠,...)如果您如果您更愿意公开
AlertVisibility
,您将来可能会遇到以下问题 - 试想一下,较新版本的 WPF 摆脱了烦人的 Visibility 枚举,在这种情况下,您必须修改 ViewModel 以公开新的 Visibility 基础结构/属性,以保持 View 正常工作,但这是当 View 行为封装在 ViewModel 中时,从 MVVM 的角度来看,这是不正确的。因此,保持简单并公开简单的bool AlertVisible
属性。编辑:关于评论中的命名建议
绝对同意!我建议将
AmountVisible
重命名为IsAmountSpecified
或类似的名称。In your case you have definite business rule
Shown WHEN > 10k
, it should be encapsulated in ViewModel rather than View because View is aware on HOW data will be shown rather then WHEN and WHY.So I would suggest exposing both
Amount
andShowAlert
properties and avoid exposingAlertVisibility
property because it scatter such WPF View specific things like Visibility enum states (Hidden, Collapsed, ...)If you would prefer to expose
AlertVisibility
you could face following problem in the future - just imagine that newer versions of WPF got rid of the annoying Visibility enum and in this case you've to modify ViewModel to expose new Visibility infrastructure/property to keep View working fine, but this is not correct from the MVVM perspectives when a View behaviour encapsulated in ViewModel. So Keep it Simple and expose straightforwardbool AlertVisible
property.EDIT: Regarding naming suggestion in the comment
Absolutely agree! I would suggest renaming
AmountVisible
toIsAmountSpecified
or something like this.我将通过转换器将视图的警报图标可见性绑定为金额值,该转换器采用金额为 10000 的参数。转换器将返回可见或折叠。
您还可以让虚拟机在超过阈值时发送一条消息,并且任何愿意侦听该消息的视图或其他视图模型都可以对该消息做出反应。
I would have my view's alert icon visibility bound Amount value through a converter which takes a parameter of the amount of 10000. The converter would return visible or collapsed.
You could also have the VM send a message when it's over the threshold and any view or other viewmodels who care to listen for it can react to the message.