How to control the scroll position of a ListBox in a MVVM WPF app

后端 未结 4 585
后悔当初
后悔当初 2020-12-05 18:05

I have got a big ListBox with vertical scrolling enabled, my MVVM has New and Edit ICommands. I am adding new item to the end of the collection but I want the scrollbar also

4条回答
  •  独厮守ぢ
    2020-12-05 18:38

    Using this in MVVM can be easily accomplished via an attached behavior like so:

    using System.Windows.Controls;
    using System.Windows.Interactivity;
    
    namespace Jarloo.Sojurn.Behaviors
    {
        public sealed class ScrollIntoViewBehavior : Behavior
        {
            protected override void OnAttached()
            {
                base.OnAttached();
                AssociatedObject.SelectionChanged += ScrollIntoView;
            }
    
            protected override void OnDetaching()
            {
                AssociatedObject.SelectionChanged -= ScrollIntoView;
                base.OnDetaching();
            }
    
            private void ScrollIntoView(object o, SelectionChangedEventArgs e)
            {
                ListBox b = (ListBox) o;
                if (b == null)
                    return;
                if (b.SelectedItem == null)
                    return;
    
                ListBoxItem item = (ListBoxItem) ((ListBox) o).ItemContainerGenerator.ContainerFromItem(((ListBox) o).SelectedItem);
                if (item != null) item.BringIntoView();
            }
        }
    }
    

    Then in the View ad this reference at the top:

    xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    

    And do this:

    
             
                 
             
    
    

    Now when the SelectedItem changes the behavior will do the BringIntoView() call for you.

提交回复
热议问题