ContentTemplate recreated on selection

2 posts, 0 answers
  1. Anthony
    Anthony avatar
    41 posts
    Member since:
    Apr 2012

    Posted 23 May 2014 Link to this post

    I'm working on a UI and I have a nested tab control. The main tab control has a series of tabs tied to an ItemsSource. The inner tab control is organizational and every item represented in the main tab will have a set number of tabs. All of it works great except I noticed that when I selected between tabs that the inner tab of the previous one was reset to the first tab even if I had the second selected.

    I did some digging and discovered that the contents of the ContentTemplate are recreated each time a tab is selected. That seems pretty inefficient, but I guess there's some good reason for that? At any rate, I'm hoping someone has a good alternative to this behavior without resorting to creating the tabs programmatically (that'd be kludgey from my view-model).

    Here's a simplified example of what I'm talking about. The contents of UserControl1 aren't shown, but they can be anything that has visual state that isn't persisted to the model -- e.g. current tab, unbound text, et al.

    ​<Window ...>
        <Window.Resources>
            <DataTemplate x:Key="TabHeaderTemplate">
                <TextBlock Text="{Binding Name, Mode=OneWay}" />
            </DataTemplate>
            <DataTemplate x:Key="TabContentTemplate">
                <local:UserControl1 DataContext="{Binding Path=.}" />
            </DataTemplate>
        </Window.Resources>
        <Grid>
            <telerik:RadTabControl ItemsSource="{Binding Path=.}"
                                   ItemTemplate="{StaticResource TabHeaderTemplate}"
                                   ContentTemplate="{StaticResource TabContentTemplate}" />
        </Grid>
    </Window>
  2. Anthony
    Anthony avatar
    41 posts
    Member since:
    Apr 2012

    Posted 23 May 2014 in reply to Anthony Link to this post

    Well, I figured I would find a solution after I posted a question about it. I just didn't realize it would be so quick. The answer is to set the IsContentPreserved property to true.

    ​<telerik:RadTabControl ItemsSource="{Binding Path=.}"
                           ItemTemplate="{StaticResource TabHeaderTemplate}"
                           ContentTemplate="{StaticResource TabContentTemplate}"
                           IsContentPreserved="True" />
  3. UI for WPF is Visual Studio 2017 Ready
Back to Top