title: Scroll WPF ListBox to the SelectedItem set in code in a view model
body: <p>I have a XAML view with a list box:</p>
  
  <pre><code>&lt;control:ListBoxScroll ItemSource="{Binding Path=FooCollection}"
                         SelectedItem="{Binding SelectedFoo, Mode=TwoWay}"
                         ScrollSelectedItem="{Binding SelectedFoo}"&gt;
      &lt;!-- data templates, etc. --&gt;
  &lt;/control:ListBoxScroll&gt;
  </code></pre>
  
  <p>The selected item is bound to a property in my view. When the user selects an item in the list box my SelectedFoo property in the view model gets updated. When I set the SelectedFoo property in my view model then the correct item is selected in the list box.</p>
  
  <p>The problem is that if the SelectedFoo that is set in code is not currently visible I need to additionally call <code>ScrollIntoView</code> on the list box. Since my ListBox is inside a view and my logic is inside my view model ... I couldn't find a convenient way to do it. So I extended ListBoxScroll:</p>
  
  <pre><code>class ListBoxScroll : ListBox
  {
      public static readonly DependencyProperty ScrollSelectedItemProperty = DependencyProperty.Register(
          "ScrollSelectedItem",
          typeof(object),
          typeof(ListBoxScroll),
          new FrameworkPropertyMetadata(
              null,
              FrameworkPropertyMetadataOptions.AffectsRender, 
              new PropertyChangedCallback(onScrollSelectedChanged)));
      public object ScrollSelectedItem
      {
          get { return (object)GetValue(ScrollSelectedItemProperty); }
          set { SetValue(ScrollSelectedItemProperty, value); }
      }
  
      private static void onScrollSelectedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
      {
          var listbox = d as ListBoxScroll;
          listbox.ScrollIntoView(e.NewValue);
      }
  }
  </code></pre>
  
  <p>It basically exposes a new dependency property <code>ScrollSelectedItem</code> which I bind to the <code>SelectedFoo</code> property on my view model. I then hook into the property changed callback of the dependent property and scroll the newly selected item into view.</p>
  
  <p>Does anyone else know of an easier way to call functions on user controls on a XAML view that is backed by a view model? It's a bit of a run around to: </p>
  
  <ol>
  <li>create a dependent property</li>
  <li>add a callback to the property changed callback</li>
  <li>handle function invocation inside the static callback</li>
  </ol>
  
  <p>It would be nice to put the logic right in the <code>ScrollSelectedItem { set {</code> method but the dependency framework seems to sneak around and manages to work without actually calling it.</p>