WPF。 MVVM。使用事件是一种不好的语气吗?
使用 MVVM 模式时,事件的使用是否被认为是不好的并且所有 UI 逻辑都应该通过命令来实现?
Is usage of events considered bad and all UI logic should be implemented via commands when using MVVM pattern?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
值得思考一下 MVVM 模式真正为您带来了什么。
如果在代码隐藏中处理 UI 事件不禁止上述行为,那么就没有问题!
就我个人而言,如果可以的话,我会使用命令,但不担心是否需要一些隐藏代码。
It is worth thinking about what the MVVM pattern really gives you.
If handling UI events in code behind doesn't prohibit the above, then there is no problem!
Personally I use commands if I can, but am not concerned if there is a little code-behind required.
要添加到 ColinE 的答案中,可以使用事件,但允许代码隐藏事件的问题是它是一个滑坡。您添加一件事,然后添加另一件事,突然间您在代码隐藏类中创建了实际逻辑。 (如果您与团队中其他经验不足的程序员一起工作,这一点就更加突出)。
这就是为什么我更喜欢(几乎没有例外)根本不编写代码隐藏。
每个适合代码隐藏但不是真正的应用程序逻辑代码的代码也可以在行为中编写,这使得架构更加严格且易于定义。
此外,行为作为 WPF4 的一个强大补充,本质上是非常封装的并且非常可重用,所以通常无论以何种标准衡量,使用行为都会更好。
To add to ColinE's answer, events can be used, but the problem with allowing codebehind events is that it's a slippery slope. you add one thing, then you add another, and all of a sudden you create actual logic in the codebehind class. (It's even more prominent if you are working with other less experienced programmers in your team).
That's why I prefer, to almost no exceptions, to not write codebehind AT ALL.
Every code that fits the codebehind without being really application-logic code can also be written within a Behavior, which makes the architecture much more strict and simple to define.
Also, Behaviors, being such a strong addition to WPF4, are by their nature very encapsulated and very reusable, so usually you're better off with a Behavior by any standard.
这取决于事件的使用方式。我相信如果您使用事件来实现 UI 特定效果,那就没问题。毕竟,您的视图定义了 UI 的行为方式,因此它甚至是将 UI 特定逻辑放在视图后面的代码中的正确位置。
但是,您的应用程序/业务逻辑应该位于 ViewModel 或 Model 中。在这种情况下,如果绑定不起作用并且需要事件,则所有事件处理程序应该将所有逻辑委托给 ViewModel。
It depends on how event is used. I believe you are fine if you use event for UI specific effects. After all, your view defines how UI behaives, so it's even a right place to put your UI specific logic in code behind within your view.
However, your application/business logic supposed to be in the ViewModel or Model. In such case, if binding doesn't do the job and event is necessary, all event handler should do is to delegate all logic to ViewModel.