如何在视图模型中动态构建 UI
我的 silverlight 应用程序完全采用了 MVVM 模式。然而,我们的一些 UI 是数据驱动的。主要有两个项目...
菜单。我们正在使用 Infragistics XamMenu。菜单
我们有一个“仪表板”,允许用户添加“管理单元”。这有点像 iGoogle 等门户网站。
在上述两种情况下,UI 都需要在运行时构建。目前,我正在后面的代码中运行代码,因为我没有看到访问 ViewModel 中的 UI 树的简单方法。
为了在视图中运行代码,我在 ViewModel 中创建了一个事件,该事件在加载数据后触发。因此,我必须在后面的视图代码中混入对视图模型的引用。我不喜欢它,它非常丑陋......所以基本上有两个问题:
如何让视图从视图模型获取数据已加载的消息,而不直接引用视图中的视图模型代码落后?目前,我从数据上下文中提取引用。
是否可以在视图模型中构建 UI 并使用数据绑定。我想知道是否可以将内容控件的“内容”绑定到视图模型中的某种类型(不确定该类型是什么)?当然,不好的部分是视图模型的可测试性似乎消失了。可以这样使用绑定吗?
I have wholly adopted the MVVM pattern for our silverlight app. However, some of our UI is data driven. Mainly two items...
The menu. We are using Infragistics XamMenu.
We have a "dashboard" which allows users to add "snap-ins". This is sort of like a portal site such as iGoogle.
In both cases above the UI needs to be built at runtime. Currently I am running the code in the code behind because I don't see an easy way to access the UI tree in the ViewModel.
In order to run the code in the view I have created an event in the ViewModel that fires once the data is loaded. So, I have to kludge a reference to the viewmodel in the view code behind. I don't like it an it is very ugly... so basically two question:
How can I have the view get a message from the viewmodel that the data is loaded without getting a direct reference to the viewmodel in the view code behind? Currently I pull the reference from the data context.
Is it possible to build the UI in the view model and use data binding. I was wondering if I could bind the "content" of a contentcontrol to some type (not sure what the type would be) in the viewmodel? Of course, the bad part about this is the testability of the view model seems to go away. Can binding be used this way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要回答问题 1,为什么不使用 MVVM 轻型“Messenger”类。
在您看来,您可以通过以下方式注册监听消息:
其中 DoSomething 是一个接受布尔参数(例如)的方法。
然后,要从视图模型发送消息,请执行以下操作:
希望有帮助:)您需要将其添加到您的使用中:
To answer question 1, why dont you make use of the MVVM light "Messenger" class.
In your view,you register to listen to a message in the following way:
Where DoSomething is a method that takes in a boolean parameter (for example).
Then, to send the message from your view model, you do the following:
Hope that helps :) You'll need to add this to your usings: