c# – 递归创建新实例的是什么?
发布时间:2020-12-15 20:59:49 所属栏目:百科 来源:网络整理
导读:在MainModelView中,我有以下内容: // constructor public MainViewModel(IDataService dataService,INavigationService navigationService) { SelectedSystemItem = _systems.Where(x = x.Key == Properties.Settings.Default.SASE).First(); } private Key
在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} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |