C# 从TabItem的ContextMenu访问TabControl

C# 从TabItem的ContextMenu访问TabControl,c#,wpf,mvvm,datagrid,tabcontrol,C#,Wpf,Mvvm,Datagrid,Tabcontrol,WPF dataGrid中的行数与TabControl中的TabItems数同步。 请参考图片 . 现在,当我在DataGrid的contextMenu中单击删除一行时,即一个TabItem也将被删除。要执行此操作,我希望导航到代码中的特定选项卡控件,并删除与DataGridRow同步的TabItem 到目前为止,我能够删除DataGrid中的行,但无法从TabControl中删除特定的TabItem //Code to Delete the DataGridRow from D

WPF dataGrid中的行数与TabControl中的TabItems数同步。 请参考图片 . 现在,当我在DataGrid的contextMenu中单击删除一行时,即一个TabItem也将被删除。要执行此操作,我希望导航到代码中的特定选项卡控件,并删除与DataGridRow同步的TabItem

到目前为止,我能够删除DataGrid中的行,但无法从TabControl中删除特定的TabItem

        //Code to Delete the DataGridRow from DataGrid Collection
        //Get the clicked MenuItem
        var menuItem = (MenuItem)sender;
        //Get the ContextMenu to which the menuItem belongs
        var contextMenu = (ContextMenu)menuItem.Parent;
        //Find the placementTarget
        var item = (DataGridRow)contextMenu.PlacementTarget;
        //Get the underlying item, that you cast to your object that is bound
        //to the DataGrid (and has subject and state as property)
        var toDeleteFromBindedList = item.DataContext as IndHazardViewModel;
        DataContextHARAFunVM.HazardsCollection.Remove(toDeleteFromBindedList);

我需要从ContextMenu导航到TabControl的代码帮助。

如果TabItem有viewModel集合,请将其从集合中删除。否则直接从选项卡控件中删除它。现在是什么阻止了您?即使我正在从集合中删除/删除,它也在删除DataGridRow。但是,要从TabControl中删除TabItem,我需要无法获取的TabControl。在while循环中使用VisualTreeHelper.FindParent(object)方法查找TabControl您可以使用VisualTreeHelper.GetParent(TabItem)获取TabControl您声明这是MvvM,然后从视图模型中的集合中删除dataItem。如果操作正确,Grid和TabControl将具有相同的
ItemsSource
。因此,当您影响其中一个时,它将自动更新另一个。如何填充ItemsSource?你们用装订吗?
        //Code to Delete the DataGridRow from DataGrid Collection
        //Get the clicked MenuItem
        var menuItem = (MenuItem)sender;
        //Get the ContextMenu to which the menuItem belongs
        var contextMenu = (ContextMenu)menuItem.Parent;
        //Find the placementTarget
        var item = (DataGridRow)contextMenu.PlacementTarget;
        //Get the underlying item, that you cast to your object that is bound
        //to the DataGrid (and has subject and state as property)
        var toDeleteFromBindedList = item.DataContext as IndHazardViewModel;
        DataContextHARAFunVM.HazardsCollection.Remove(toDeleteFromBindedList);