问题
Please assist with MVVM design/understanding problem.
Given that we have a Windows Phone app with following UI structure:
MainPage.xaml body:
<views:PanoramaView/>
DataContext is set via MVVM Light view-model locator to a static MainViewModel class instance.
Views/PanoramaView.xaml body:
<UserControl.DataContext>
<ViewModels:PanoramaViewModel/>
</UserControl.DataContext>
<StackPanel x:Name="LayoutRoot">
<controls:Panorama Background="{Binding PanoramaBackgroundBrush}"
ItemsSource="{Binding PanoramaItems}"
ItemTemplate="{StaticResource panoramaItemTemplate}"
/>
</StackPanel>
At that point I have stumbled upon a question - What should I do in case I want all my PanoramaItems to be comprised of a different user controls? If I define a panorama item template, I doom all of them to be alike. But my intention is to have serveral, compeltely different panorama items. I wanted to have a class (presumably PanoramaViewModel
) that would allow me control which panorama items are displayed at a given moment of time.
So there has to be a way for me to still stick to MVVM, but to be able to instantiate new Views(Panorama Items) and inject them into a PanoramaItems
collection of my PanoramaViewModel
. Where and how do I do that?
回答1:
You have to define resource key to define a data template with view setter for the view item being rendered for the different view model class types, and derive VM classes from a common base class (PanoramaViewModel, i.e)
回答2:
In WPF I should have use a DataTemplateSelector to work around my design problem. Since Windows Phone apps are more like Silverlight, I can implement it myself. A good example of how is in this article and this silverlight.net forum thread.
来源:https://stackoverflow.com/questions/7373410/databound-windows-phone-panorama-with-mvvm-design