I have a problem with the selected item in WPF-TabControl that could be reproduced with the following simplified code:
If a new TabItem is created and selected through the Click-event of the button in the second window, the tab is created, added and selected. When the second window will be closed, the selected item of the tab-control is reset to the last selected item. The problem occurs in my MVVM-app and it is independent of the Items-collection. I can use the ItemsSource or the Items-Collection, it happens always.
Has someone an idea what happens here or has a nice workaround?
TabControl tabControl = new TabControl() ;
tabControl.Items.Add(new TabItem { Header="InitialTabItem"});
((TabItem)tabControl.Items[0]).Focus();
Window mainWindow = new Window() { Content=tabControl,Title="TabControl-Window"};
mainWindow.Show();
Button addButton = new Button() { Content="AddTabItem"};
addButton.Click += (o, e) => {
TabItem newTabItem=new TabItem(){Header=DateTime.Now.ToLongTimeString()};
tabControl.Items.Add(newTabItem);
tabControl.SelectedItem = newTabItem;
};
Window directorWindow = new Window() { Owner = mainWindow ,Content=addButton,Height=80,Width=200,Title="DirectorWindow"};
directorWindow.Show();
Update
It seems to be as always when I have bigger problems with WPF, to be an issue with focus-management. If I change the creation-code as follows, it works:
TabItem newTabItem=new TabItem(){Header=DateTime.Now.ToLongTimeString()};
tabControl.Items.Add(newTabItem);
Dispatcher.BeginInvoke(new Action(delegate{
newTabItem.Focus();
tabControl.SelectedItem = newTabItem;
}), System.Windows.Threading.DispatcherPriority.Input, null);
However it looks not very confidently to me. Some ideas?