是什么以递归方式创建新实例?

时间:2016-05-09 13:55:24

标签: c# wpf mvvm-light

在MainModelView中,我有以下内容:

    // 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();
        }
    }

ViewModelLocator中的某个地方:

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

LocationsPageViewModel是从ViewModelBase派生的空类。

LocationPage.xaml

页面标记中的

DataContext="{Binding LocationsPageVM, Source={StaticResource Locator}}"

的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>

问题是我正在获得堆栈溢出,因为每次我获取新的MainViewModel实例时都会出现(因为在var vm = locator.LocationsPageVM调试器跳转到MainViewModel的构造函数之后)。在此死循环期间,定位器对象每次都是新的。所以我期待着解这是什么导致这个死循环。

1 个答案:

答案 0 :(得分:0)

我认为这一行会导致ViewModelLocator重新实例化

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

尝试删除它们。另请注意,mvvm light将这些行放到MainWindow.xaml

DataContext={StaticResource Locator, Binding Main}