title: Show last item in ListBox
body: <p>I have a bound listBox that is defined in XAML this way</p>
  
  <pre><code>&lt;ListBox ItemsSource="{Binding Messages}" ItemTemplateSelector="{StaticResource lc_messageTemplateSelector}"
            ScrollViewer.HorizontalScrollBarVisibility="Disabled" HorizontalContentAlignment="Stretch" 
           SelectedItem="{Binding SelectedMessage, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
           IsSynchronizedWithCurrentItem="True" VirtualizingPanel.ScrollUnit="Pixel" Background="White"
           ItemContainerStyle="{StaticResource NakedListBoxItem}"&gt;
      &lt;ListBox.ItemsPanel&gt;
          &lt;ItemsPanelTemplate&gt;
              &lt;VirtualizingStackPanel VerticalAlignment="Bottom" /&gt;
          &lt;/ItemsPanelTemplate&gt;
      &lt;/ListBox.ItemsPanel&gt;
      &lt;ListBox.Resources&gt;
      &lt;/ListBox.Resources&gt;
      &lt;i:Interaction.Behaviors&gt;
          &lt;classes:ScrollIntoViewBehavior /&gt;
      &lt;/i:Interaction.Behaviors&gt;
  </code></pre>
  
  <p>I do make a request to a web-service to get needed records and fill the Messages - ObservableCollection, all items are shown as needed, the problem I have, is after I load all the items I need to make visible the last one.
  So I set it</p>
  
  <pre><code>SelectedMessage = Messages.Last();
  </code></pre>
  
  <p>By default this doesn't work using databinding, so I created (found it on SO) a behavior for this</p>
  
  <pre><code>public sealed class ScrollIntoViewBehavior : Behavior&lt;ListBox&gt;
      {
          protected override void OnAttached()
          {
              base.OnAttached();
              AssociatedObject.SelectionChanged += ScrollIntoView;
          }
  
          protected override void OnDetaching()
          {
              AssociatedObject.SelectionChanged -= ScrollIntoView;
              base.OnDetaching();
          }
  
          private static void ScrollIntoView(object o, SelectionChangedEventArgs e)
          {
              Selector selector = o as Selector;
              if (selector is ListBox)
              {
                  (selector as ListBox).ScrollIntoView(selector.SelectedItem);
              }
          }
      }
  </code></pre>
  
  <p>But this doesn't work. </p>
  
  <p>What could be wrong here and how to make it work using data binding.</p>
  
  <p>Could it be to the fact that some items have a complex DataTemplate which have the Image control that loads images in async mode and changes the size of the ListBox and then scrolling act wrong?</p>
  
  <p>What I see is that sometimes it will show the last element, sometimes it will scroll to a random one, could not find a relation when it works the right way.</p>
  
  <p>Thx</p>