微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 递归创建新实例的是什么?

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

解决方法

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

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

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

DataContext={StaticResource Locator,Binding Main}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐