title: Accessing the ScrollViewer of a ListBox from C#
body: <p>I'd like to change the properties of a <code>ScrollViewer</code> of a <code>ListBox</code> from C#.</p>
  
  <p>I found <a href="https://stackoverflow.com/questions/263485/how-do-you-access-the-scrollviewer-element-of-a-listbox-control-in-silverlight-c">this question</a> here on Stackoverflow. I took the accepted answer's advice and exposed the <code>ScrollViewer</code> as a property of a subclass. However, this doesn't appear to be working in an example shown below. Some of the comments in that question also state that this technique didn't work.</p>
  
  <p>XAML:</p>
  
  <pre><code>&lt;Window x:Class="StackoverflowListBoxScrollViewer.MainWindow"
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
          Title="MainWindow" Height="350" Width="525"&gt;
  
  &lt;/Window&gt;
  </code></pre>
  
  <p>C#:</p>
  
  <pre><code>using System;
  using System.Windows;
  using System.Windows.Controls;
  
  namespace StackoverflowListBoxScrollViewer
  {
      public class MyListBox : ListBox
      {
          public ScrollViewer ScrollViewer
          { get { return (ScrollViewer)GetTemplateChild("ScrollViewer"); } }
      }
  
      public partial class MainWindow : Window
      {
          public MainWindow()
          {
              InitializeComponent();
  
              var myListBox = new MyListBox();
  
              Content = myListBox;
  
              myListBox.Items.Add(new Button() { Content = "abc" });
              myListBox.Items.Add(new Button() { Content = "abc" });
              myListBox.Items.Add(new Button() { Content = "abc" });
              myListBox.Items.Add(new Button() { Content = "abc" });
              myListBox.Items.Add(new Button() { Content = "abc" });
  
              var button = new Button() { Content = "Check ScrollViewer" };
              button.Click += (s, e) =&gt;
                  {
                      if (myListBox.ScrollViewer == null)
                          Console.WriteLine("null");
                  };
              myListBox.Items.Add(button);
          }
      }
  }
  </code></pre>
  
  <p>When I click the "Check ScrollViewer" button, it prints "null". I.e., the <code>ScrollViewer</code> wasn't retrieved.</p>
  
  <p>How do I get to that darn <code>ScrollViewer</code>? :-)</p>