MVVM 在代码隐藏中具有 UI 特定事件
我有一个 Silverlight 页面,该页面几乎没有控件,并且所有行为都不是数据绑定的。例如,RichTextBox 是 Text 属性的数据绑定。但诸如粗体、斜体、编号等控件行为是由控件上方工具栏的按钮单击事件驱动的。这些控件确实会更改数据的值,但实际上并不保存/检索数据。那么,与在 ViewModel 中创建 ICommand 对象相比,将此类 UI 事件保留在 Silverlight 页面的代码隐藏页面中是否可以?
MVVM 表示您的 View 应该与 ViewModel 交互,以便在内部与 Model 交互。这里视图只是更新视图而不是模型。那么对于此类事件,代码隐藏可以吗?
I have a Silverlight page that has few controls and all of the behaviors are not databound. For example, RichTextBox is databound for the Text property. But the controls behaviors like Bold, Italic, Numbered, etc are driven from a button click event from toolbar above the control. These controls do change the value of the Data, but do not actually save/retrieve the data. So, is it ok to keep such UI events in code-behind page of the Silverlight page than creating a ICommand object in ViewModel?
MVVM says your View should interact with ViewModel for interacting with Model internally. Here the View is just updating the View and not the Model. So is Code-Behind for such events is fine?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这种事情可能非常主观,但请记住 ViewModel 是视图的模型,包括视图显示方式的设置。我的按钮等连接到 ViewModel 中的 ICommand(例如,谷歌搜索“DelegateCommand”或“RelayCommand”),而不是视图中的命令。然后,我的 ViewModel 根据需要更新其状态,并且视图响应事件。即使 VM 除了触发事件以供视图响应(并处理事件的异常和日志记录等)之外,按钮单击也会循环通过 ViewModel。
对于视图中不影响其使用的数据的复杂行为,当然在代码隐藏中处理事件是合适的,尽管我通常发现用户控件而不是窗口等中是这种情况。
This kind of thing can be quite subjective, but remember that the ViewModel is the model of the view including settings for how the view is displayed. I have my buttons etc connect to ICommands in the ViewModel (google for 'DelegateCommand' or 'RelayCommand' for examples), not commands in the View. My ViewModel then updates its state as necessary and the View responds to events. Button clicks loop through the ViewModel, even if the VM does nothing other than fire events for the View to respond to (and handle exceptions and logging etc for the event).
For complex behaviour in the view which does not affect the data that it works with then of course handling events in the code-behind is appropriate, though I usually find this is the case in user controls, not windows etc.