元素已经是另一个元素的子元素 - PivotItems

时间:2016-08-10 20:49:14

标签: c# uwp mvvm-light

我目前正在崩溃,我不知道其来源或解决方案的原因。

我的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有关。

如何正确创建对象以便不抛出此错误,我可以在数据透视页面和其他页面之间导航而不会崩溃?

1 个答案:

答案 0 :(得分:0)

我想我已经复制了你的问题:

enter image description here

这是因为您的ItemsSoucePivotItem控件的集合:ObservableCollection<PivotItem>。当您返回TabMainPage public ObservableCollection<PivotItem> PivotItems { get; set; }时,同一PivotItem秒被添加到Pivot

以下是OnNavigatingFrom的{​​{1}}方法中的解决方案:

TabMainPage