将命令绑定到子窗口的数据上下文
我有一个名为 MAINWINDOW 的窗口,它有一个工具栏和一个框架。框架内显示一个称为主页的页面。此页面有一个树视图,其中显示菜单选项。当用户单击节点时,相应的表单(页面)将使用 Border.Content 属性显示在 HOMEPAGE 的边框内。我的工具栏中有一个按钮用于搜索客户,我需要将此按钮的命令属性绑定到在客户页面的视图模型中定义的命令。此页面是 HOMEPAGE 的子页面,而 HOMEPAGE 又是 MAINWINDOW 的子页面。您能否建议一种方法来执行此操作,即访问子对象的子对象中定义的命令? 谢谢。
I have a window called MAINWINDOW that has a toolbar and a frame. Inside the frame is shown a Page called HOMEPAGE. This page has a treeview where menu options are shown. When the user clicks a node, the corresponding form (a Page) is shown inside a border in HOMEPAGE, using the Border.Content property. I have a button in the toolbar to search for customers and I need to bind this button's command property to a command which is defined inside the Customers page's viewmodel. This page is a child of the HOMEPAGE which in turn is a child of MAINWINDOW. Can you suggest a way to do this, that is to access a command defined in a child's child object?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这违背了 MVVM 的原则。
ViewModel(及其相应的命令)与视图是 1:1。每个 ViewModel 服务于一个视图,并且仅服务于一个视图。将 ViewModel 视为 View 的代码隐藏是有帮助的,只是它永远不能直接访问 View(因此它与 View 完全解耦)。
违反这一原则(V 到 VM == 1:1),会在 ViewModel 之间或 View 之间创建依赖关系,这是一件坏事。它使您的应用程序更难维护,因为每个“模块”都依赖于其他“模块”的实现。
您应该做的是在为相关视图提供服务的 ViewModel 上公开另一个命令。该命令反过来可以触发你想要的任何事情。
That goes against the principles of MVVM.
ViewModels (and their corresponding Commands) are 1:1 to Views. Each ViewModel serves one View, and one View ONLY. It helps to think of the ViewModel as the codeBehind of the View, only that it can never access the View directly (thus it's completely decoupled from it).
Violating this principle (V to VM == 1:1), creates dependencies between ViewModels or between Views, which is a bad thing. It makes your application harder to maintain since each "module" is dependent on the implementation of other "modules".
What you should do is expose another Command on the ViewModel that serves the relevant View. That Command in turn could trigger what ever you want.