Search code examples
c#wpftabcontroltabitem

Unable to cast object of type 'System.Windows.Controls.Grid' to type 'System.Windows.Controls.TabItem'


Hi there i have define more than one tabItem in my TabControl. tabItem1, tabItem2, tabItem3

these are CloseableTabItem.

if i add a node in tabItem1 and press a button to make a subGraph model for this node. the

same node should be appear in tabItem2 so that tabItem2-Header = nodeName and nodeName =

tabItem1-Header.

Without (TabItem)tabControl.SelectedContent == tabItem1, the code work correct but the

Problem ist if i added a new node in tabItem2 and press the subGraph-Button node will be

added to tabItem3 but the nodeName = tabItem1-Header.

my Code throw an Exception "Unable to cast object of type 'System.Windows.Controls.Grid' to type 'System.Windows.Controls.TabItem'."

MyNodeData todata = new MyNodeData();
if (tabItem1.IsLoaded && (TabItem)tabControl.SelectedContent == tabItem1)
{
  string childNodeName = (String)tabItem1.Header;
  todata.Text = childNodeName;
  return;
}
 if (tabItem2.IsLoaded)
{
  string childNodeName = (String)tabItem2.Header;
  todata.Text = childNodeName;
  return;
}
 if (tabItem3.IsLoaded)
{
  string childNodeName = (String)tabItem3.Header;
  todata.Text = childNodeName;
  return;
}

Solution

  • SelectedContent is the content of the TabItem. What you want is SelectedItem.