我目前正在崩溃,我不知道其来源或解决方案的原因。
我的VM上有一个ViewModelLocator,它已在构造函数中注册(
ctor { ... SimpleIoc.Default.Register<TabMainViewModel>(); }
public TabMainViewModel TabMainVm => ServiceLocator.Current.GetInstance<TabMainViewModel>();
然后,XAML将此VML用作静态资源
DataContext="{Binding Source={StaticResource ViewModelLocator}, Path=TabMainVm}"
<Pivot ItemsSource="{Binding PivotItems}">
TabMainViewModel看起来像这样:
public TabMainViewModel(MenuPivotFactory factory)
{
PivotItems = new ObservableCollection<PivotItem>(factory.PivotItems);
}
public ObservableCollection<PivotItem> PivotItems { get; set; }
工厂由ServiceLocator(也已注册)注入,它只是创建了一个PivotItem的列表
/*NavigationHelper*/
private static readonly IDictionary<Type, Type> ViewModelRouting
= new Dictionary<Type, Type>
{
{typeof(MonitorViewModel), typeof(MonitorView)},
{typeof(RouteViewModel), typeof(RouteView)},
{typeof(MapViewModel), typeof(MapView)}
}
public static Page GetView(Type viewModel)
{
return (Page)Activator.CreateInstance(ViewModelRouting[viewModel]);
}
/*Factory*/
new PivotItem
{
Header = new TabHeader {Label = "Monitor", Glyph = "\uE121"},
Content = NavigationHelper.GetView(typeof(MonitorViewModel))
},
我希望这会使我的对象创建过程有点清晰。
现在我可以毫无问题地在不同的PivotItem之间导航。但是当我离开时,然后按下后退按钮有时它会起作用,有时我会被标题中提到的错误抛入App.g.i.cs:元素已经是另一个元素的子元素。
在进行调试时,我得到了View调用VMs PivotItems属性的get方法然后抛出此错误的点。所以我假设它与PivotItems中的Views有关。
如何正确创建对象以便不抛出此错误,我可以在数据透视页面和其他页面之间导航而不会崩溃?