In my C# WPF Application I have a TabControl which has a model as an item source. In each TabItem a TreeView is created, which is also filled with data from the model.
My problem is that when I switch through the tabs of the TabControl, the selected items and expanded items collapse.
Do I need to save and load the selected and expanded items inside the Model everytime I switch the TabItems?
I created a small example to reproduce it:
Model
public class ProjectModel
{
public string Name { get; set; }
public ObservableCollection<string> Structure { get; set; }
}
XAML
<TabControl x:Name="tcTest" >
<!-- TabControl Style -->
<TabControl.Resources>
<Style TargetType="TabItem" BasedOn="{StaticResource {x:Type TabItem}}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabItem}">
<Grid SnapsToDevicePixels="true">
<Border Padding="8,3" BorderThickness="1,1,1,0" Height="27" Background="CadetBlue" >
<DockPanel>
<TextBlock Text="{Binding Name}" />
</DockPanel>
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</TabControl.Resources>
<!-- TabControl Content Template -->
<TabControl.ContentTemplate>
<DataTemplate>
<StackPanel>
<TreeView ItemsSource="{Binding Path=Structure}"/>
</StackPanel>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
C#
public ObservableCollection<ProjectModel> Projects = new ObservableCollection<ProjectModel>();
public MainWindow()
{
InitializeComponent();
Projects.Add(new ProjectModel
{
Name = "Test",
Structure = new ObservableCollection<string>
{
"Item 1",
"Item 2",
"Item 3",
"Item 4",
}
});
Projects.Add(new ProjectModel
{
Name = "Help",
Structure = new ObservableCollection<string>
{
"Item 5",
"Item 6",
"Item 7",
"Item 8",
}
});
tcTest.ItemsSource = Projects;
}
Unfortunately yes, you need to notice selected and collapsed items if you want to keep them, though I would say, that it belongs more to the ViewModel, not to the Model.
TabControlhas only one so to say "visualization" ofContentTemplatefor the current tab, if you switch to another tab onlyDataContextof this "visualization" being changed. So, as the same controls being filled with new data, all selections etc. go lost. If you add e.g. an emptyTextBox, which isn't data bound, to the content'sDataTemplatefill it by first tab, you will see the input also by the other tabs.Optionally you can try to handle it in the view layer, below is an example how you can notice the selection. You can so try to extend it to notice multiple selection and/or collapse state.
Update for hierarchical template: