如何处理操作子视图的父视图命令,并且视图建模会很乏味或不需要?

发布于 2024-12-01 09:27:07 字数 517 浏览 1 评论 0原文

我知道将视图模型绑定到视图是可以的,包含视图模型的视图模型也可以,包含视图的视图也可以。我遇到的情况似乎是子视图需要绑定到视图。

特别是,我有一种情况,特定命令的实现不需要以任何方式存在或操作视图模型(并且也不会影响底层模型模型)。我可以将命令放入视图模型中,绑定它并执行它,但这确实是一种代码味道,妨碍了视图模型层与视图层的干净分离。

该命令从父视图发起,但影响子视图。我可以想出几种方法来处理这个问题。

  • 在父级中添加一个事件处理程序,以某种方式找到正确的子级(不知道如何在 Silverlight 中做到这一点),然后执行我需要的所有逻辑。
  • 处理父级中的事件,但重新引发不同的事件(双重调度)。在子进程中,处理第二个事件,并执行逻辑。
  • 将命令绑定到父视图并处理命令本身(或父视图提供的委托中)的逻辑。
  • 直接将命令绑定到子视图。在这种情况下,我如何指定父视图的 xaml 中到右子视图/控件的绑定?
  • 将命令绑定到上面定义的子视图的视图模型。

我应该怎么办?

I know binding a view model to a view is ok, view models containing view models is ok, and views containing views is ok. I have a situation where it seems a sub-view needs to be bound to a view.

In particular, I have a case where a particular command's implementation does not need to be in nor manipulate a view model in any way (and doesn't affect the underlying model-model either). I could put the command in a view model, bind it, and execute it, but that's a definite code smell preventing clean separation of the view model layer from the view layer.

The command is initiated from a parent view, but affects a child view. I can think of several ways to handle this.

  • Add an event handler in the parent, somehow find the right child (not sure how to do that in Silverlight), and then do all the logic I need.
  • Handle the event in the parent, but re-raise a different event (double dispatch). In the child, handle the second event, and do the logic.
  • Bind the command to the parent and handle the logic in the command itself (or in the parent view's supplied delegate).
  • Bind the command to the child view directly. In this case how would I specify the binding in the parent view's xaml to the right child view/control?
  • Bind the command to the child view's view model as defined above.

What should I do?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

时光病人 2024-12-08 09:27:07

MVVM 的“无代码隐藏”规则并不意味着适用于仅与 UI 相关的代码,例如设置焦点、运行动画、调整大小等。因此,在您的情况下,我会将代码在你的视图后面,并且只有一个视图引用另一个视图。

如果您的业务逻辑代码保留在您的 ViewModel 中,并且您的演示/UI 代码保留在您的视图后面,那么您就可以了。

The "No-Code-Behind" rule for MVVM is not meant to apply to code that is only related to the UI, such as setting focus, running animations, adjusting sizes, etc. So in your case, I'd put the code behind your Views, and just have one View reference the other.

Providing your Business Logic code stays in your ViewModels, and your Presentation/UI code stays behind your Views, you're good.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文