【问题标题】:What creates new instances recursively?什么递归地创建新实例?
【发布时间】:2016-05-09 13:55:24
【问题描述】:

在 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 的构造函数)。在此死循环期间,定位器对象每次也是新的。所以我很期待了解是什么导致了这个死循环。

【问题讨论】:

  • 标签清晰

标签: c# wpf mvvm-light


【解决方案1】:

我想这行会导致 ViewModelLocator 的重新实例化

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

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

DataContext={StaticResource Locator, Binding Main}

【讨论】:

    猜你喜欢
    • 2015-05-10
    • 1970-01-01
    • 2017-05-11
    • 2017-02-20
    • 2019-06-13
    • 1970-01-01
    • 2018-12-20
    • 2018-11-16
    • 1970-01-01
    相关资源
    最近更新 更多