ViewModelLocator 是否应该消除 DataTemplate 的必要性?
我确信我错过了一些简单的东西(在这个 mvvm 东西上仍然有点绿色),但我认为 ViewModelLocator 的使用消除了 DataTemplate 将视图绑定到视图模型的需要。但出于某种原因,我似乎仍然需要它。
在 WPF 应用程序中,我有一个窗口,其唯一内容是绑定到默认绑定的内容模板。
<Window ... DataContext="{Binding MainView, Source={StaticResource Locator}}">
<grid><ContentControl Content="{Binding}"/></grid>
然后我有一个 UserControl,我想你可以说它是真正的视图 - 视图模型。
<UserControl ...
DataContext="{Binding MainView, Source={StaticResource Locator}}">
...xaml...
</UserControl>
我注意到,除非我将绑定视图 - 视图模型(本例中为 MainView)的 DataTemplate 放置在 App.xaml 中,否则我只会获得类的名称。
由于窗口的数据上下文是使用定位器绑定的,我认为这会起作用。我的猜测是,窗口中使用 ContentControl 的附加层令人困惑。
如果我将 ContentControl 替换为对视图的直接引用,即。
<view:MainView />
这也有效。所以我想我有两个问题: 1. 为什么绑定似乎不理解这一点? 2. 有没有办法使用定位器让它工作?我希望窗口具有最小的用户界面,并将大部分内容保留在用户控件中。
感谢您提供任何信息。
模糊
I am sure I am missing something simple (still a bit green on this mvvm stuff), but I thought that the use of ViewModelLocator removed the need of DataTemplate binding view to viewmodel. But for some reason I seem to still need it.
In a WPF application I have a window whose only content is a content template which binds to default binding.
<Window ... DataContext="{Binding MainView, Source={StaticResource Locator}}">
<grid><ContentControl Content="{Binding}"/></grid>
I then have a UserControl which I guess you could say is the real view - viewmodel.
<UserControl ...
DataContext="{Binding MainView, Source={StaticResource Locator}}">
...xaml...
</UserControl>
What I have noticed is that unless I place DataTemplate which binds view - viewmodel (MainView in this case) in App.xaml, I just get the name of the class.
Since the window's datacontext is bound using the locator, I thought this would work. My guess is that the additional layer in the window using the ContentControl is confusing things.
If I replace the ContentControl with a direct reference to the view, ie.
<view:MainView />
This also works. So I guess I have two questions:
1. Why does the binding not seem to understand this?
2. Is there a way to get this to work using the locator? I would like to have the window with minimal ui, and keep the bulk in UserControls.
Thank you for any information.
Obscured
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
每个内容控件可以容纳任何对象,如果您只分配类而不使用 DataTemplate,则默认情况下将其转换为字符串。 DataTemplate 说明了内容应如何可视化,包括绑定(应获取和评估对象的哪些属性)。
ViewModelLocator 与 DataTemplates 没有任何关系,它只是根据名称或您想要的任何内容为您找到正确的视图模型。这是如何解耦创建/定位视图模型的逻辑并将其放在一个地方的方法。
each content control can hold any object, if you just assign class without DataTemplate, this is by default translated to string. DataTemplate says how the content should be visualized, including bindings (which propeties of your object should be taken and evaluated).
ViewModelLocator doesn't have anything with DataTemplates, it just locates the right view model for you based on name or whatever you want. It is the way how to decouple logic of creating/locating view models and put this at one place.