title: Using ScrollViewer inside another ScrollViewer control template - why are they synchronized
body: <p>If I replace a <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.scrollviewer.aspx" rel="nofollow noreferrer">ScrollViewer</a> control template so that it contains another scroll viewer then some of the time they scroll together.</p>
  
  <p>For example the <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.aspx" rel="nofollow noreferrer">GridView</a> class has a variation on the following template which ensures that the column headers always line up with the contents of the list view, even when the user scrolls to the right (in this sample "Columns" is a <code>GridViewColumnCollection</code> filled with columns)</p>
  
  <pre><code>&lt;ScrollViewer HorizontalScrollBarVisibility="Visible"&gt;
      &lt;ScrollViewer.Style&gt;
          &lt;Style TargetType="{x:Type ScrollViewer}"&gt;
              &lt;Setter Property="Template"&gt;
                  &lt;Setter.Value&gt;
                      &lt;ControlTemplate TargetType="{x:Type ScrollViewer}"&gt;
                          &lt;DockPanel&gt;
                              &lt;ScrollViewer DockPanel.Dock="Top"&gt;
                                  &lt;GridViewHeaderRowPresenter Columns="{StaticResource Columns}" /&gt;
                              &lt;/ScrollViewer&gt;
                              &lt;ScrollBar DockPanel.Dock="Bottom" Name="PART_HorizontalScrollBar" Orientation="Horizontal"
                                          Minimum="0.0" Maximum="{TemplateBinding ScrollableWidth}" ViewportSize="{TemplateBinding ViewportWidth}"
                                          Value="{Binding Path=HorizontalOffset,RelativeSource={RelativeSource TemplatedParent},Mode=OneWay}"  /&gt;
                              &lt;ScrollContentPresenter Name="PART_ScrollContentPresenter" Content="{TemplateBinding Content}" /&gt;
                          &lt;/DockPanel&gt;
                      &lt;/ControlTemplate&gt;
                  &lt;/Setter.Value&gt;
              &lt;/Setter&gt;
          &lt;/Style&gt;
      &lt;/ScrollViewer.Style&gt;
      &lt;GridViewHeaderRowPresenter Columns="{StaticResource Columns}" /&gt;
  &lt;/ScrollViewer&gt;
  </code></pre>
  
  <p>How does this work?</p>
  
  <p><img src="https://i.stack.imgur.com/wxesM.png" alt="Magic!"></p>
  
  <p>(I'm asking because I need to modify the <code>GridView</code> templates and I've managed to break this functionality - I'm trying to work out how to fix it but finding it difficult because I don't understand why it works in the first place!)</p>