1

I have a TabControl whose items, which are ViewModels are dynamically populated. Also, there is a UserControl linked to a ViewModel in the DataTemplate. Everything is working and displaying fine. However, the constructor of SecurityRoleControl is only created once, no matter how many tabs there are. I need to add processing logic during construction of a UserControl but the problem is that it is only called once in the application. Can someone please tell me the reason for this behavior and possibly any work around? Highly appreciated. Thanks in advance.

// MainWindow.XAML code
<TabControl
  IsSynchronizedWithCurrentItem="True"
  ItemsSource="{Binding ElementName=AdminMainWindow, Path=Workspaces}"
  ItemTemplate="{StaticResource ClosableTabItemTemplate}"
  Margin="4">
</TabControl>

// Data Template in Dictionary
<DataTemplate x:Key="ClosableTabItemTemplate">
  <DockPanel Width="120">
    <Button 
        Command="{Binding Path=CloseCommand}"
        Content="X"
        Cursor="Hand"
        DockPanel.Dock="Right"
        Focusable="False"
        FontFamily="Courier" 
        FontSize="9"
        FontWeight="Bold"  
        Margin="0,1,0,0"
        Padding="0"
        VerticalContentAlignment="Bottom"
        Width="16" Height="16" />
    <ContentPresenter 
        Content="{Binding Path=DisplayName}" 
        VerticalAlignment="Center" />
  </DockPanel>
</DataTemplate>

// Binding of ViewModel to UserControl
<DataTemplate DataType="{x:Type vm:SecurityRoleViewModel}">
  <uc:SecurityRoleControl />
</DataTemplate>

// Code to add a ViewModel to Workspace
SecurityRoleViewModel workspace = new SecurityRoleViewModel("Security Role Search");
workspace.MRN = viewModel.MRN;
workspaces.Add(workspace);
ICollectionView collectionView = CollectionViewSource.GetDefaultView(workspaces);
if (collectionView != null) {
  collectionView.MoveCurrentTo(workspace);
}

// Workspaces
public ObservableCollection<WorkspaceViewModel> Workspaces { get { return workspaces; } }

// Constructor of SecurityRoleControl, which is called only once
public SecurityRoleControl() {
  InitializeComponent();
}
SajidQ
  • 158
  • 1
  • 9
  • 1
    Believe it's answered quite well here: http://stackoverflow.com/questions/4993159/why-do-tab-controls-reuse-view-instances-when-changing-tab – Colin Smith Jun 17 '13 at 16:23
  • Please refer to the accepted answer for this [question](http://stackoverflow.com/questions/2080764/how-to-preserve-control-state-within-tab-items-in-a-tabcontrol) – Suresh Jun 17 '13 at 18:29

0 Answers0