I have following code:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="145" Width="156">
<Window.Resources>
<DataTemplate x:Key="tabTemplate">
<ScrollViewer>
<StackPanel Orientation="Vertical">
<TextBlock>x</TextBlock>
<TextBlock>x</TextBlock>
<TextBlock>x</TextBlock>
<TextBlock>x</TextBlock>
<TextBlock>x</TextBlock>
<TextBlock>x</TextBlock>
<TextBlock>x</TextBlock>
</StackPanel>
</ScrollViewer>
</DataTemplate>
</Window.Resources>
<Grid>
<TabControl>
<TabItem Header="Tab1" ContentTemplate="{StaticResource ResourceKey=tabTemplate}"/>
<TabItem Header="Tab2" ContentTemplate="{StaticResource ResourceKey=tabTemplate}"/>
</TabControl>
</Grid>
</Window>
What is weird is the behavior of scrollbars – if I scroll down on the first tab and switch to second tab, the scrollbar is down too – position of the scrollbars is synchronized when the tab items have the same data templates. Do you know about any solution of this issue?
In addition, when I alter the code and make two data templates (one for each tab), the scrollbars are not preserving their position at all – that means if I scroll down on tab1, switch to tab2 and to tab1 again, the scrollbar is on default position. Any solution of this one?
To enable the
DataTemplateto create separate instances for each usage, just set thex:Sharedattribute toFalse:That will cause your second issue, which is preserving the UI when the tab changes. According to WPF UI persistence in TabControl, the solution would be to use a different
ItemsControlthat looks like aTabControl.