using System.Collections.Specialized;
using System.Windows.Controls;
using System.Windows.Interactivity;
using System.Windows.Media;

namespace ZadaniaWPF
{

    public class PrzesunięcieWDółListyPoDodaniuElementu : Behavior<ListBox>
    {
        ListBox listBox;

        protected override void OnAttached()
        {
            listBox = this.AssociatedObject;
            if (listBox != null) ((INotifyCollectionChanged)listBox.Items).CollectionChanged += ListBox_CollectionChanged;
        }

        private void ListBox_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if(e.Action == NotifyCollectionChangedAction.Add || e.Action == NotifyCollectionChangedAction.Reset)
            {
                if (VisualTreeHelper.GetChildrenCount(listBox) > 0)
                {
                    Border border = (Border)VisualTreeHelper.GetChild(listBox, 0);
                    ScrollViewer scrollViewer = (ScrollViewer)VisualTreeHelper.GetChild(border, 0);
                    scrollViewer.ScrollToBottom();
                }
            }
        }
    }
}