How to scroll to the bottom of a ScrollViewer automatically with Xaml and binding?

前端 未结 6 1586
一生所求
一生所求 2020-12-01 05:57

I\'ve got a TextBlock whose content is data bound to a string property of the ViewModel. This TextBlock has a ScrollViewer wrapped aro

6条回答
  •  温柔的废话
    2020-12-01 06:35

    From Geoff's Blog on ScrollViewer AutoScroll Behavior.

    Add this class:

    namespace MyAttachedBehaviors
    {
        /// 
        ///     Intent: Behavior which means a scrollviewer will always scroll down to the bottom.
        /// 
        public class AutoScrollBehavior : Behavior
        {
            private double _height = 0.0d;
            private ScrollViewer _scrollViewer = null;
    
            protected override void OnAttached()
            {
                base.OnAttached();
    
                this._scrollViewer = base.AssociatedObject;
                this._scrollViewer.LayoutUpdated += new EventHandler(_scrollViewer_LayoutUpdated);
            }
    
            private void _scrollViewer_LayoutUpdated(object sender, EventArgs e)
            {
                if (Math.Abs(this._scrollViewer.ExtentHeight - _height) > 1)
                {
                    this._scrollViewer.ScrollToVerticalOffset(this._scrollViewer.ExtentHeight);
                    this._height = this._scrollViewer.ExtentHeight;
                }
            }
    
            protected override void OnDetaching()
            {
                base.OnDetaching();
    
                if (this._scrollViewer != null)
                {
                    this._scrollViewer.LayoutUpdated -= new EventHandler(_scrollViewer_LayoutUpdated);
                }
            }
        }
    }
    

    This code depends Blend Behaviors, which require a reference to System.Windows.Interactivity. See help on adding System.Windows.Interactivity.

    If you install the MVVM Light NuGet package, you can add a reference here:

    packages\MvvmLightLibs.4.2.30.0\lib\net45\System.Windows.Interactivity.dll
    

    Ensure that you have this property in your header, which points to System.Windows.Interactivity.dll:

    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
    

    Add a Blend Behavior into the ScrollViewer:

    
        
    
    

    Example:

    
        
            
                
            
            
        
     
    

    We have to add a definition for the namespace, or else it won't know where to find the C# class we have just added. Add this property into the tag. If you are using ReSharper, it will automatically suggest this for you.

    xmlns:implementation="clr-namespace:MyAttachedBehaviors"
    

    Now, if all goes well, the text in the box will always scroll down to the bottom.

    The example XAML given will print the contents of the bound property LogText to the screen, which is perfect for logging.

提交回复
热议问题