处理数据模板
是否有一些我不知道的处理 DataTemplates 的明显方法?
例如:
我有一个 ContentControl,它将用于显示各种应用程序视图。据我所知,对于每个控件,每种数据类型可能存在一个数据模板。 (即,我可以将 DataTemplate 添加到 ResourceDictionary,以在 ContentControl 将 PersonViewModel 设置为其 DataContext 时显示 DetailsView,或者在 ContentControl 将 PersonManagerViewModel 设置为其 DataContext 时显示 ListView)。但是,当 ContentControl 的 DataContext 设置为 PersonViewModel 时,我该如何在 DetailsView 和 EditView 之间进行选择呢?
Is there some obvious method for dealing with DataTemplates of which I am unaware?
For instance:
I have a ContentControl which will be used to display the various application views. As far as I am aware, for each control there may exist one DataTemplate per DataType. (i.e. I could add a DataTemplate to the ResourceDictionary to display a DetailsView when the ContentControl has a PersonViewModel set as its DataContext or a ListView when the ContentControl has a PersonManagerViewModel set as its DataContext). But how might I go about choosing between a DetailsView and an EditView when the ContentControl's DataContext is set to a PersonViewModel?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
几个选项:
定义“区域”视图模型时,始终在 ViewModel 和视图之间使用 1:1 映射。这是最典型的做法。如果您正在考虑对多个视图使用相同的 ViewModel,则 ViewModel 可能做得太多了。共享逻辑可能属于两个或多个不同 ViewModel 类将使用的自己的 Model 类。
定义自定义 DataTemplateSelector 以消除可能的匹配项之间的歧义。这有点难看,因为您不再具有“查找默认”行为的神奇魔力。
仅允许其中一个模板为“默认”。其他模板必须由需要它们的特定视图通过 Key 引用。
A few options:
When defining 'region' View Models, always use a 1:1 map between a ViewModel and a View. This is the most typical approach. If you're thinking of using the same ViewModel for multiple Views, it's likely that the ViewModel is doing too much. The shared logic probably belongs in its own Model class that two or more different ViewModel classes would use.
Define a custom DataTemplateSelector to disambiguate between possible matches. This is a bit uglier, as you no longer have the nice magic 'find the default' behavior.
Only allow one of the templates to be the 'default'. Other templates must be referenced by Key by the specific Views that need them.
最灵活的解决方案是使用 DataTemplateSelector让您以编程方式根据您想要的条件选择要使用的模板。
我们在一些地方使用的另一种选择是简单地使用多个 ViewModel;在您的情况下,您可以为 DetailsView 使用 ReadOnlyPersonViewModel,为 EditView 使用 MutablePersonViewModel。
The most flexible solution is to use a DataTemplateSelector to let you programmatically choose which template to use, based on whatever conditions you want.
Another alternative that we used in a few places is to simply use multiple ViewModels; in your case, you could have a ReadOnlyPersonViewModel for the DetailsView and a MutablePersonViewModel for the EditView.