Monday, 16 April 2012

ScrollViewer AutoScroll Behavior

Overview
This behavior causes a ScrollViewer to automatically scroll to the bottom when it's contents change size. It is useful for TextBox controls inside ScrollViewers so that the cursor doesn't disappear whilst typing.


The Behavior


    public class AutoScrollBehavior : Behavior<ScrollViewer>
    {
        private ScrollViewer _scrollViewer = null;
        private double _height = 0.0d;

        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 (this._scrollViewer.ExtentHeight != _height)
            {
                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);
        }
    }

Implementation in XAML

<ScrollViewer Height="200">
    <i:Interaction.Behaviors>
        <cmd:AutoScrollBehavior />
    </i:Interaction.Behaviors>
    <TextBox IsEnabled="{Binding Path= IsCommentEnabled}" Text="{Binding Path=Comment, Mode=TwoWay}" MinHeight="200"
        AcceptsReturn="True" InputScope="Text" TextWrapping="Wrap">
    </TextBox>
/ScrollViewer>

No comments:

Post a Comment