1

I am new in MVVM Light. I try to write a project with MVVM Light Framework and I have some questions. I have defined my MainWindow.xaml like this:

MainWindow.xaml:

<Grid x:Name="LayoutRoot">
    <Grid.RowDefinitions>
        <RowDefinition Height="30"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <StackPanel Orientation="Horizontal">
        <Button Height="30" Width="40" Command="{Binding OpenNews}">News</Button>
        <Button Height="30" Width="40" Margin="5,0,0,0" Command="{Binding OpenTeams}">Teams</Button>
    </StackPanel>
    <ContentPresenter  Grid.Row="1" Content="{Binding CurrentViewModel}"/>
</Grid>

MainViewModel: Contains the two RelayCommands OpenNews and OpenTeams. And also the CurrentViewModel property. This property contains the ViewModel depending on the option which the user clicks (NewsViewModel or TeamsViewModel).I do that like this:

    private void ShowOpenTeams()
    {
        CurrentViewModel = ServiceLocator.Current.GetInstance<TeamsViewModel>(); //MainViewModel.TeamsViewModel;
    }

    private void ShowOpenNews()
    {
        CurrentViewModel = ServiceLocator.Current.GetInstance<NewsViewModel>();
    }

app.xaml: I have defined the relation between ViewModel's DataType and the View that should be shown.

<Application.Resources>
    <DataTemplate DataType="{x:Type vm:NewsViewModel}">
        <view:NewsView/>
    </DataTemplate>
    <DataTemplate DataType="{x:Type vm:TeamsViewModel}">
        <view:TeamView/>
    </DataTemplate>        
    <!--Global View Model Locator-->
    <vm:ViewModelLocator x:Key="Locator"
                         d:IsDataSource="True" />
</Application.Resources>

The question is: why do I need the ViewModelLocator in this case? Does using ViewModelLocator make sense with this approach? I don't see any benefit...

The Views in MVVM Light are created with this relation DataContext="{Binding ViewModelName, Source={StaticResource Locator}}" but I wonder which approach is it usefull with?

MrScf
  • 2,407
  • 5
  • 27
  • 40
  • related http://stackoverflow.com/questions/5462040/what-is-a-viewmodellocator-and-what-are-its-pros-cons-compared-to-datatemplates – kenny Mar 15 '15 at 22:01
  • The ViewModelLocator is his implementation of an inversion of control container for dependency injection, I usually switch it out for Castle.Windsor and do all my di in app.xaml.cs. – reggaeguitar Mar 15 '15 at 22:01
  • @reggaeguitar Do you know any sample to see in action the ViewModelLocator? It seems,I don't need ViewModelLocator With DataTemplates... – MrScf Mar 15 '15 at 22:12
  • Here I instanciate first the ViewModel. I set every time the right ViewModel in the property CurrentViewModel and the data is shown through the defined DataTemplates. How can I instanciate View and pass as parameter the right ViewModel? I guess the IoC Container creates the view and pass the view model parameter – MrScf Mar 15 '15 at 22:32

0 Answers0