What creates recursive instances?

In MainModelView, I have the following:

    // constructor
    public MainViewModel(IDataService dataService, INavigationService navigationService)
    {
        SelectedSystemItem = _systems.Where(x => x.Key == Properties.Settings.Default.SASE).First();
    }

    private KeyValuePair<int, string> _selectedSystemItem;
    public KeyValuePair<int, string> SelectedSystemItem
    {
        get
        {
            return _selectedSystemItem;
        }
        set
        {
            Set(ref _selectedSystemItem, value);
            var locator = (ViewModelLocator)Application.Current.Resources["Locator"];
            var vm = locator.LocationsPageVM;
            vm.UpdateCells();
        }
    }

somewhere in the ViewModelLocator:

    ...
    SimpleIoc.Default.Register<LocationsPageViewModel>();
    ...
    public LocationsPageViewModel LocationsPageVM
    {
        get
        {
            return ServiceLocator.Current.GetInstance<LocationsPageViewModel>();
        }
    }

LocationsPageViewModelis an empty class derived from ViewModelBase.

LocationPage.xaml

DataContext="{Binding LocationsPageVM, Source={StaticResource Locator}}" in the page tag.

App.xaml

<Application x:Class="Generator.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:vm="clr-namespace:Generator.ViewModel"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:ignore="http://www.galasoft.ch/ignore"
             StartupUri="MainWindow.xaml"
             mc:Ignorable="d ignore">

    <Application.Resources>
        <!--Global View Model Locator-->
        <vm:ViewModelLocator x:Key="Locator"
                             d:IsDataSource="True" />
    </Application.Resources>

</Application>

The problem is that I get a stack overflow because it appears every time I get a new instance of MainViewModel (because after var vm = locator.LocationsPageVM the debugger jumps to the MainViewModel constructor). The Locator object is also new every time during this dead loop. So I look forward to understanding what this dead cycle is doing.

+4
source share
1 answer

I assume this line causes the ViewModelLocator to be re-created

var locator = (ViewModelLocator)Application.Current.Resources["Locator"];
var vm = locator.LocationsPageVM;
vm.UpdateCells();

. , mvvm MainWindow.xaml

DataContext={StaticResource Locator, Binding Main}
0

All Articles