Click here to Skip to main content
13,800,885 members
Click here to Skip to main content
Add your own
alternative version

Stats

5K views
7 bookmarked
Posted 9 Aug 2018
Licenced CPOL

[WPF] Easiest Way to Create a Animated/Smoothed Scroll Bar

, 9 Aug 2018
Rate this:
Please Sign up or sign in to vote.
Here's the Best , Beauty and Easiest way to create a animated and & smooth sliding scroll viewer in WPF Platform ( Windows Presentation Foundation )

Introduction

Beholds...

Smooth Sliding & Animated Scrollbar ! Brilliant !!!! Isn't it ?!

Perhaps many of you have been thinking of something like that and then you went to Google it!

And of course you thought it should be easy to make stuffs like that in the WPF!

... and just after some pathetic and hopeless momments , you face the unknown world of confusing codes , random answers , new controllers and ... !

Well , don't give up ! There's still a really easy way to create it in a Perfect Shape !

 

Result / GIF 30fps

 

Why You Shouldn't Use Custom Control For Now ?

  •  If you're an expert :

Forget it! yeah I was just kidding :\  you can build everything you want !

A Custom Control or even a Serial Killer Robot Rexter !  :D

 

  • If you're not an expert :

All themes are mounted on a specific resource in WPF and if you create yourown custom control It dosen't support the general resources you have to add them one by one your own !

 

Creating the Bases

First of all , Create a Window and Apply your theme [ mahapps , materialDesign , ModernUI , etc. ]

// I Use My Custom Theme

 

Window XAML:

<Window x:Class="Tutorial_Projects.SmoothScroll_Window"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

        xmlns:local="clr-namespace:Tutorial_Projects"

        Title="Easiest Way to Create a Animated/Smoothed Scroll Bar | By NeoTrix2000" Height="338.866" Width="553.846" ResizeMode="NoResize" WindowStartupLocation="CenterScreen">
    
<Grid Background="#FF232323">
        <ScrollViewer Margin="0">
            <RichTextBox Foreground="#FF959595" BorderBrush="{x:Null}" Background="#FF212121" IsReadOnly="True" IsHitTestVisible="False">
                <FlowDocument>
                    <Paragraph>
                        <Run Foreground="#FF0E95AA" FontWeight="Bold" FontSize="18"/>
                    </Paragraph>
                    <Paragraph>
                        <Run Foreground="#FF0E95AA" FontWeight="Bold" FontSize="18" Text="Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque"/>
                    </Paragraph>
                    <Paragraph>
                        <Run Foreground="#FF0E95AA" FontWeight="Bold" FontSize="18" Text=" "/>
                        <Run Text="laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat. Sed ut perspiciatis unde omnis iste natus error sit "/>
                    </Paragraph>
                    <Paragraph>
                        <Run Text="voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus "/>
                    </Paragraph>
                    <Paragraph>
                        <Run Text="maiores alias consequatur aut perferendis doloribus asperiores repellat. Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint"/>
                    </Paragraph>
                </FlowDocument>
            </RichTextBox>
        </ScrollViewer>

    </Grid>
</Window>

 

Remember to use "Auto" height on everything is inside the scrollview.

Going to the Next Stage!

  1. Now , You just need to duplicate scrollview to 2 Scrollview !
  2. Rename the first one to "main_scroll" and second one to "scroll_animator"
  3. Now , change the child of scroll_animator to a empty group .
  4. Bind the Height property of empty group to the ActualHeight property of RichTextBox is inside main_scroll.
  5. Well Done !

 

Time to Code!

  • Before we start this section , you need to know WPF standard scrollview doesn't support direct value setting by code in Offset , it's a function like set it to 1 , 2 , 3 ! it Sucks !
  • Then we need to add the offset property manually , it's really easy to create !
  1. Add a class to your project root . Add Item > Class > ScrollViewFixer.cs
  2. Add this code to your Class & Save it !

 

ScrollViewFixer.cs

 

//// After Namespace
public class ScrollViewFixer: ScrollViewer {
 public static DependencyProperty v_offsetProperty = DependencyProperty.Register("v_offset", typeof(double), typeof(ScrollViewFixer), new PropertyMetadata(new PropertyChangedCallback(OnVerticalChanged)));
 public static DependencyProperty h_offset = DependencyProperty.Register("h_offset", typeof(double), typeof(ScrollViewFixer), new PropertyMetadata(new PropertyChangedCallback(OnHorizontalChanged)));
 

private static void OnVerticalChanged(DependencyObject ss_dependency, DependencyPropertyChangedEventArgs ss_evenargs) {
  ScrollViewFixer viewer = ss_dependency as ScrollViewFixer;
  viewer.ScrollToVerticalOffset((double) ss_evenargs.NewValue);
 }
 

private static void OnHorizontalChanged(DependencyObject ss_dependency, DependencyPropertyChangedEventArgs ss_evenargs) {
  ScrollViewFixer viewer = ss_dependency as ScrollViewFixer;
  viewer.ScrollToHorizontalOffset((double) ss_evenargs.NewValue);
 }


 public double CurrentHorizontalOffset {
  get {
   return (double) this.GetValue(h_offset);
  }
  set {
   this.SetValue(h_offset, value);
  }
 }


 public double v_offset {
  get {
   return (double) this.GetValue(v_offsetProperty);
  }
  set {
   this.SetValue(v_offsetProperty, value);
  }

 }
}
+ Remember , Add this code to your cs file Namespace .
  • Now let's finish it ...

 

  • Change main_scroll like this :

Replace :

<ScrollViewer x:Name="main_scroll" Margin="0">

With :

<fixed_scrl:ScrollViewFixer x:Name="main_scroll" Margin="0,0,18,0" VerticalScrollBarVisibility="Hidden">
  • Add the name space in top of window in xmlns :
xmlns:fixed_scrl="clr-namespace:Scroll_Fixer_Namespace"

Remember the "Scroll_Fixer_Namespace" is your namespace of "ScrollViewFixer.cs" file.

namespace Scroll_Fixer_Namespace
{
    public class ScrollViewFixer : ScrollViewer
    { ....

 

  • Resize scroll_animator to just "Scroll Bar" box size.
  • Time to animate !
Process :
  1. Add a ScrollChanged Event to scroll_animator.
  2. Create Animator Code ( don't forget to add using System.Windows.Media.Animation; ) :

<scroll_animator> ScrollChanged Event :

private void scroll_animator_ScrollChanged(object sender, ScrollChangedEventArgs e) {
 PowerEase _ease = new PowerEase();
 _ease.EasingMode = EasingMode.EaseOut;
 _ease.Power = 8;
 DoubleAnimation scrollanim = new DoubleAnimation(scroll_animator.VerticalOffset, TimeSpan.FromSeconds(2));
 scrollanim.EasingFunction = _ease;
 main_scroll.BeginAnimation(Scroll_Fixer_Namespace.ScrollViewFixer.v_offset_property, scrollanim);
}
I'm a bigfan of PowerEase :D If you want change it to normal Ease for smoother result .

 

Well done ! now if you change your scrollbar it's smooth and so fantastic ! BUT BUGGY :|

Now we're going to fix ...

 

Fixing Scrollview Issues

A > Fixing Mousewheel Scrolling :

  • Add PreviewMouseWheel to your main_scroll
  • Disable Handler and Connect it to Animator , It's Like :
private void MouseWheel_Fix(object sender, MouseWheelEventArgs e)
{ e.Handled = true;}

 

  • EXTRA MODE :
private void MouseWheel_Fix(object sender, MouseWheelEventArgs e) {

 e.Handled = true;
 int Division_Unit = 5;
 scroll_animator.ScrollToVerticalOffset((scroll_animator.VerticalOffset + ((e.Delta * -1) / Division_Unit)));

}

B > Fixing Dynamic Content :

If you're using a dynamic frameworkelement like ListBox , Editbox , Textbox , RichText , Stackpanel you need to set the scroll bar update on adding things , changes  ...

  • Create a function UpdateAnimator() to your Code Behind
private void UpadeUpdateAnimator()
{
      scroll_animator.ScrollToEnd();
}
  • Now add SizeChanged to your main_scroll and just insert UpadeUpdateAnimator(); to it !
private void Content_Size_Change(object sender, SizeChangedEventArgs e)
{
    if (this.IsLoaded) {  /// Startup Fix
        UpadeUpdateAnimator();
    }

}
  • And in every update you make in Main ScrollView Contents , Just use a little UpadeUpdateAnimator(); after works!

 

We're done ! Enjoy from your amazing , smoothed , animated ScrollView !!!

In the next article I will show you how to animate by scroll function like HTML5 Responisve sites and a lot of security articles I'm working on ... Cya !

Regards ,

HamidMemar as TheNeoTrix2000

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

TheNeoTrix2000
Iran (Islamic Republic of) Iran (Islamic Republic of)
This is your last chance. After this, there is no turning back. You take the blue pill - the story ends, you wake up in your bed and believe whatever you want to believe. You take the red pill - you stay in Wonderland and I show you how deep the rabbit-hole goes. - Matrix

You may also be interested in...

Pro

Comments and Discussions

 
QuestionGreat Article With A Lot of Value Pin
Hyland Computer Systems11-Aug-18 12:38
memberHyland Computer Systems11-Aug-18 12:38 
AnswerRe: Great Article With A Lot of Value Pin
TheNeoTrix200017-Aug-18 13:41
memberTheNeoTrix200017-Aug-18 13:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01 | 2.8.181215.1 | Last Updated 9 Aug 2018
Article Copyright 2018 by TheNeoTrix2000
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid