There is an very old WPF application of Hyper Tree - http://blogs.msdn.com/b/llobo/archive/2007/10/31/mindmap-app-using-hyperbolic-tree.aspx.
The source code can be found at codeplax.com -
http://hypertree.codeplex.com/releases/view/11524
I wanted to use this tree control in my silverlight application. Now the issue is that i am new to silverlight, and the code is using some WPF specific things.
Please suggest me to solve my problem.
Thanks in advance.
Abhinav
Update:
things like
FrameworkPropertyMetadata and FrameworkPropertyMetadataOptions, InvalidateVisual(), OnRender override, child UIElements.
Code Added:
public class SmartBorder : Decorator
{
#region Dependency Properties
public static readonly DependencyProperty GlowBrushProperty =
DependencyProperty.Register("GlowBrush", typeof(Brush), typeof(SmartBorder), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));
......
#region Dependency Property backing CLR properties
......
#endregion
// if the button is pressed, this fires
private static void OnRenderIsPressedChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
SmartBorder border = o as SmartBorder;
if (border != null)
{
if ((bool)e.NewValue == true)
{
border.BorderBrush = Brushes.Transparent;
border.BorderWidth = 2;
}
else
{
border.BorderBrush = Brushes.Red;
border.BorderWidth = 2;
}
border.InvalidateVisual();
}
}
// if the mouse is over the control, this fires
private static void OnRenderIsMouseOverChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
SmartBorder border = o as SmartBorder;
if (border != null)
{
border.InvalidateVisual();
}
}
// a series of methods which all make getting the default or currently selected brush easier
protected override void OnRender(DrawingContext dc)
{
Rect rc = new Rect(0, 0, this.ActualWidth, this.ActualHeight);
LinearGradientBrush gradientOverlay = GetGradientOverlay();
Brush glowBrush = GetGlowBrush();
Brush backBrush = GetBackgroundBrush();
Brush borderBrush = GetBorderBrush();
Pen borderPen = new Pen(borderBrush, BorderWidth);
double cornerRadiusCache = CornerRadius;
// draw the highlight as necessary
if (RenderIsMouseOver)
{
Rect rcGlow = rc;
double glowMove = BorderWidth * 2;
rcGlow.Inflate(glowMove, glowMove);
glowMove = 0;
rcGlow.Offset(new Vector(glowMove, glowMove));
dc.DrawRoundedRectangle(GetOuterGlowBrush(), null, rcGlow, cornerRadiusCache, cornerRadiusCache);
}
// we want to clip anything that might errantly draw outside of the smart border control
dc.PushClip(new RectangleGeometry(rc, cornerRadiusCache, cornerRadiusCache));
dc.DrawRoundedRectangle(backBrush, borderPen, rc, cornerRadiusCache, cornerRadiusCache);
dc.DrawRoundedRectangle(gradientOverlay, borderPen, rc, cornerRadiusCache, cornerRadiusCache);
if (!RenderIsPressed)
{
double clipBorderSize = BorderWidth * -4.0;
Rect rcClip = rc;
rcClip.Offset(clipBorderSize, clipBorderSize);
rcClip.Inflate(-clipBorderSize, -clipBorderSize);
dc.PushClip(new RectangleGeometry(rcClip, cornerRadiusCache, cornerRadiusCache));
dc.DrawEllipse(glowBrush, null, new Point(this.ActualWidth / 2, this.ActualHeight * 0.10), this.ActualWidth * 0.80, this.ActualHeight * 0.40);
dc.Pop();
}
// just draw the border now to make sure it overlaps everything nicely
dc.DrawRoundedRectangle(null, borderPen, rc, cornerRadiusCache, cornerRadiusCache);
dc.Pop();
//base.OnRender(drawingContext);
}
protected override Size MeasureOverride(Size constraint)
{
UIElement child = this.Child as UIElement;
double borderThickness = BorderWidth * 2.0;
if (child != null)
{
...
}
return new Size(Math.Min(borderThickness, constraint.Width), Math.Min(borderThickness, constraint.Height));
}
}
Regarding FrameworkPropertyMetadata and FrameworkPropertyMetadataOptions and value coercions etc. for Silverlight see the WPF_Compatibility solution under the ClipFlair codebase (http://clipflair.codeplex.com)
Related
I'm drawing the following Shape in a Canvas.
I would like to highlight it when it's selected by changing its color (the easy part) and drawing an small halo around it:
This is how I did using SASS: http://codepen.io/aaromnido/pen/zKvAwd/
How coud I draw in WPF? Remember that I'm drawing using the Shape's OnRender method.
Set some defaults in constructor.
One of these defaults is Shape.Effect, as it will be animated on MouseEnter event.
Construct VisualStates for Normal , and MouseEnter scenarios.
Change the VisualState of the element using VisualStateManager.GoToElementState() in MouseEnter and MouseLeave event handlers.
You can expose various properties using DPs for customization.
NewShape.cs
using System.Windows.Shapes;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows;
using System.Windows.Media.Effects;
namespace WpfStackOverflow.NewShape
{
public class CNewShape : Shape
{
public CNewShape()
{
// setting the defaults
this.Width = 40;
this.Height = 40;
this.Stroke = new SolidColorBrush() { Color = Colors.Red };
this.StrokeThickness = 5;
this.Effect = new DropShadowEffect() {
Color = Colors.Transparent,
BlurRadius = 1,
Direction = -150,
ShadowDepth = 1
};
// constructing the VisualStates
_constructVisualStates();
// event handlers
this.MouseEnter += CNewShape_MouseEnter;
this.MouseLeave += CNewShape_MouseLeave;
}
#region EventHandlers
void CNewShape_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
{
VisualStateManager.GoToElementState(this, "VSNormal", false);
}
void CNewShape_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
{
VisualStateManager.GoToElementState(this, "VSMouseEnter", false);
}
#endregion
#region Overrides
// This needs to be implemented as it is abstract in base class
GeometryGroup geo = new GeometryGroup();
protected override Geometry DefiningGeometry
{
get { return geo; }
}
protected override void OnRender(System.Windows.Media.DrawingContext drawingContext)
{
Pen pen = new Pen(this.Stroke, StrokeThickness);
drawingContext.DrawEllipse(Brushes.Transparent, pen, new Point(Width/2, Height/2), 40, 40);
drawingContext.DrawEllipse(Stroke, null, new Point(Width / 2, Height / 2), 30, 30);
base.OnRender(drawingContext);
}
#endregion
#region Helpers
private void _constructVisualStates()
{
VisualStateGroup vsg1 = new VisualStateGroup();
#region VSNormal (Normal Visual State)
VisualState stateVSNormal = new VisualState() { Name = "VSNormal" };
Storyboard sbVSNormal = new Storyboard();
ObjectAnimationUsingKeyFrames oa = new ObjectAnimationUsingKeyFrames();
Storyboard.SetTargetProperty(oa, new PropertyPath("Effect"));
DiscreteObjectKeyFrame dokf = new DiscreteObjectKeyFrame(null);
oa.KeyFrames.Add(dokf);
sbVSNormal.Children.Add(oa);
stateVSNormal.Storyboard = sbVSNormal;
vsg1.States.Add(stateVSNormal);
#endregion
#region VSMouseEnter (MouseEnter Visual State)
VisualState stateVSMouseEnter = new VisualState() { Name = "VSMouseEnter" };
Storyboard sbVSMouseEnter = new Storyboard();
ColorAnimation caStrokeColor = new ColorAnimation();
caStrokeColor.To = (Color)ColorConverter.ConvertFromString("#FF24BCDE");
Storyboard.SetTargetProperty(caStrokeColor, new PropertyPath("(Shape.Stroke).(SolidColorBrush.Color)"));
sbVSMouseEnter.Children.Add(caStrokeColor);
ColorAnimation caEffectColor = new ColorAnimation();
caEffectColor.To = (Color)ColorConverter.ConvertFromString("#FFA4E1F3");
Storyboard.SetTargetProperty(caEffectColor, new PropertyPath("(Shape.Effect).(Color)"));
sbVSMouseEnter.Children.Add(caEffectColor);
DoubleAnimation daBlurRadius = new DoubleAnimation();
daBlurRadius.To = 10;
Storyboard.SetTargetProperty(daBlurRadius, new PropertyPath("(Shape.Effect).(BlurRadius)"));
sbVSMouseEnter.Children.Add(daBlurRadius);
DoubleAnimation daDirection = new DoubleAnimation();
daDirection.To = -190;
Storyboard.SetTargetProperty(daDirection, new PropertyPath("(Shape.Effect).(Direction)"));
sbVSMouseEnter.Children.Add(daDirection);
stateVSMouseEnter.Storyboard = sbVSMouseEnter;
vsg1.States.Add(stateVSMouseEnter);
#endregion
VisualStateManager.GetVisualStateGroups(this).Add(vsg1);
}
#endregion
}
}
Usage
<local:CNewShape Canvas.Left="70" Canvas.Top="52" Stroke="#FF374095" StrokeThickness="10" Width="100" Height="100" />
Output
Quality of the image is bad. On screen actual output looks good.
Whatever your trigger is that your control enters the Highlighted state, in that trigger just set the Effect property. For my test the "trigger" is a property:
public static readonly DependencyProperty ShowShadowProperty =
DependencyProperty.Register ("ShowShadow", typeof (bool), typeof (TestShape), new PropertyMetadata (false, ShowShadowChanged));
public bool ShowShadow
{
get { return (bool)GetValue (ShowShadowProperty); }
set { SetValue (ShowShadowProperty, value); }
}
private static void ShowShadowChanged (DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((TestShape)d).OnShowShadow ();
}
private void OnShowShadow ()
{
if (ShowShadow)
{
Effect = new DropShadowEffect { Direction = 0, ShadowDepth = 20, BlurRadius = 33, Opacity = 1, Color = Colors.Black};
}
else
{
Effect = null;
}
}
Which means you don't need to do anything in OnRender.
I intended to create a Windows 8 Style App (Metro), but found out there is no support for using dual screen which is a demand for my app.
Now I am redesigning my app as a desktop application in WPF.
But I still like to mimic some nice design features from Windows 8 Apps.
One of the design features is the fly out bars typically used in a Windows 8 style app:
Bottom App bar for commands
Top Navigational bar
Right Charm that is common for all apps
The design they all have in common is a temporary flyout panel that is layered on top of the current window layout.
My question is: How can I create something similar in WPF?
I have no problem to create a main grid with a hidden bottom row that is made visible to display some common command buttons. But it would be nice to have it fly out on top of my standard layout, not squeeze it.
I know it is possible to open a new window on top of the current but that creates a bad code design and is hard to get nice looking. I would prefer to do it in the same window.
Cool question! I've actually done the charm bar fairly recently..
ideally what you need is something like
<Grid x:Name="LayoutRoot">
<Grid x:Name="Overlay" Panel.ZIndex="1000" Visibility="Collapsed">
<!-- This is where your slide out control is going to go -->
</Grid>
<!-- Use whatever layout you need -->
<ContentControl x:Name="MainContent" />
</Grid>
Now rather than squeezing the content - the Overlay grid will be on top of it similar to the charm bar! all with XAML
If you have anymore questions about this, give me a shout!
Edit; my Charm implementation - feel free to use for inspriation!
public class SlidePanel : ContentControl
{
static SlidePanel()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(SlidePanel), new FrameworkPropertyMetadata(typeof(SlidePanel)));
}
public SlidePanel()
{
EventManager.RegisterClassHandler(typeof(SlidePanel), SlidePanel.MouseEnterEvent,
new RoutedEventHandler(OnLocalMouseEnter));
EventManager.RegisterClassHandler(typeof(SlidePanel), SlidePanel.MouseLeaveEvent,
new RoutedEventHandler(OnLocalMouseLeave));
}
#region Mouse Handlers
private static void OnLocalMouseEnter(object sender, RoutedEventArgs e)
{
SetExpanded(sender, true);
}
private static void OnLocalMouseLeave(object sender, RoutedEventArgs e)
{
SetExpanded(sender, false);
}
private static void SetExpanded(object sender, bool expanded)
{
SlidePanel panel = sender as SlidePanel;
if (panel != null)
{
panel.IsExpanded = expanded;
}
}
#endregion Mouse Handlers
#region Panel Width
public double PanelWidth
{
get { return (double)GetValue(PanelWidthProperty); }
set { SetValue(PanelWidthProperty, value); }
}
// Using a DependencyProperty as the backing store for PanelWidth. This enables animation, styling, binding, etc...
public static readonly DependencyProperty PanelWidthProperty =
DependencyProperty.Register("PanelWidth", typeof(double), typeof(SlidePanel), new UIPropertyMetadata(5.0));
#endregion Panel Width
#region Closed Width
public double ClosedWidth
{
get { return (double)GetValue(ClosedWidthProperty); }
set { SetValue(ClosedWidthProperty, value); }
}
// Using a DependencyProperty as the backing store for ClosedWidth. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ClosedWidthProperty =
DependencyProperty.Register("ClosedWidth", typeof(double), typeof(SlidePanel), new UIPropertyMetadata(5.0, new PropertyChangedCallback(OnClosedWidthChange)));
#endregion Closed Width
#region Expanded Property
public bool IsExpanded
{
get { return (bool)GetValue(IsExpandedProperty); }
set { SetValue(IsExpandedProperty, value); }
}
// Using a DependencyProperty as the backing store for IsExpanded. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IsExpandedProperty =
DependencyProperty.Register("IsExpanded", typeof(bool), typeof(SlidePanel), new UIPropertyMetadata(false, new PropertyChangedCallback(OnExpandedChanged)));
#endregion Expanded Property
#region Property Changes
private static void OnExpandedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue == e.OldValue)
return;
SlidePanel panel = d as SlidePanel;
if (panel == null)
return;
bool newVal = (bool)e.NewValue;
panel.IsExpanded = newVal;
bool expanded = (bool)panel.GetValue(IsExpandedProperty);
Storyboard widthAnimation = AnimationHelper.CreateDoubleAnimation<SlidePanel>(panel, expanded,
(p, a) =>
{
a.From = (double)p.GetValue(SlidePanel.ClosedWidthProperty);
a.To = (double)p.GetValue(SlidePanel.PanelWidthProperty);
},
(p, a) =>
{
a.From = (double)p.GetValue(SlidePanel.WidthProperty);
a.To = (double)p.GetValue(SlidePanel.ClosedWidthProperty);
}, new TimeSpan(0, 0, 0, 0, 300), WidthProperty);
Timeline opacity = AnimationHelper.DoubleAnimation(0.0, 1.0, expanded,
new TimeSpan(0, 0, 0, 0, 300), OpacityProperty);
Storyboard.SetTargetName(opacity, panel.Name);
Storyboard.SetTargetProperty(opacity, new PropertyPath(OpacityProperty));
widthAnimation.Children.Add(opacity);
widthAnimation.Begin(panel);
}
private static void OnClosedWidthChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
SlidePanel panel = d as SlidePanel;
if (panel != null)
panel.Width = (double)e.NewValue;
}
#endregion Property Changes
}
A little trick I found was to have the opacity set to 0 when it wasnt expanded but set the width to 10, this then allows the user to put the mouse at the side of the screen and then it will appear after a second or so..
cheers.
Edit - As requested.. AnimationHelper.
public class AnimationHelper
{
public static Timeline DoubleAnimation(double from, double to, bool modifier, TimeSpan duration, DependencyProperty property)
{
DoubleAnimation animation = new DoubleAnimation();
if (modifier)
{
animation.From = from;
animation.To = to;
}
else
{
animation.To = from;
animation.From = to;
}
animation.Duration = new Duration(duration);
return animation;
}
public static Storyboard CreateDoubleAnimation<T>(T control, bool modifier, double from, double to, TimeSpan duration, DependencyProperty property) where T : Control
{
return
AnimationHelper.CreateDoubleAnimation<T>(control, modifier,
(p, a) =>
{
a.From = from;
a.To = to;
},
(p, a) =>
{
a.From = to;
a.To = from;
}, duration, property);
}
public static Storyboard CreateDoubleAnimation<T>(T control, bool modifier, Action<T, DoubleAnimation> onTrue, Action<T, DoubleAnimation> onFalse, TimeSpan duration, DependencyProperty property) where T : Control
{
if (control == null)
throw new ArgumentNullException("control");
DoubleAnimation panelAnimation = new DoubleAnimation();
if (modifier)
{
if (onTrue != null)
onTrue.Invoke(control, panelAnimation);
}
else
{
if (onFalse != null)
onFalse.Invoke(control, panelAnimation);
}
panelAnimation.Duration = new Duration(duration);
Storyboard sb = new Storyboard();
Storyboard.SetTargetName(panelAnimation, control.Name);
Storyboard.SetTargetProperty(panelAnimation, new PropertyPath(property));
sb.Children.Add(panelAnimation);
return sb;
}
}
I want to display an 8x8 Grid in Windows 8 metro app. To do this:
I created a Grid, and added 8 row definitions and 8 column definitions.
I then add a Rectangle with a black border to each of the grid cells.
Then in the MeasureOverride method, I check the availableSize. Since my grid needs to be square (aspect ratio = 1.0), I compute the minimum of availableSize.Width, availableSize.Height and return a new Size equal to (minimum, minimum).
However this does not work. The resulting grid's size is equal to availableSize, and not the size I return from my MeasureOverride method. If I modify the MeaureOverride, so that I set Height of RowDefinitions to minimum, and Width of ColumnDefinitions to minimum, then it works. But I saw some videos and they say you should not be explicitly setting Height & Width properties of anything.
So, is there a better way to accomplish what I want?
I'm not sure if you need to interact with those cells in any way, but if you just want to draw a grid, here is a quick control to do it. It will fill the space of the parent control.
public class GridShape : Control
{
public int Columns
{
get { return (int)GetValue(ColumnsProperty); }
set { SetValue(ColumnsProperty, value); }
}
public static readonly DependencyProperty ColumnsProperty = DependencyProperty.Register("Columns", typeof(int), typeof(GridShape), new PropertyMetadata(8));
public int Rows
{
get { return (int)GetValue(RowsProperty); }
set { SetValue(RowsProperty, value); }
}
public static readonly DependencyProperty RowsProperty = DependencyProperty.Register("Rows", typeof(int), typeof(GridShape), new PropertyMetadata(8));
public Brush Stroke
{
get { return (Brush)GetValue(StrokeProperty); }
set { SetValue(StrokeProperty, value); }
}
public static readonly DependencyProperty StrokeProperty = DependencyProperty.Register("Stroke", typeof(Brush), typeof(GridShape), new PropertyMetadata(new SolidColorBrush(Colors.Black)));
public double StrokeThickness
{
get { return (double)GetValue(StrokeThicknessProperty); }
set { SetValue(StrokeThicknessProperty, value); }
}
public static readonly DependencyProperty StrokeThicknessProperty = DependencyProperty.Register("StrokeThickness", typeof(double), typeof(GridShape), new PropertyMetadata(1.0));
protected override void OnRender(System.Windows.Media.DrawingContext drawingContext)
{
Pen pen = new Pen(Stroke, StrokeThickness);
double heightSpan = ActualHeight / Rows;
double widthSpan = ActualWidth / Columns;
for (double y = 0; y <= ActualHeight; y += heightSpan)
drawingContext.DrawLine(pen, new Point(0, y), new Point(ActualWidth, y));
for (double x = 0; x <= ActualWidth; x += widthSpan)
drawingContext.DrawLine(pen, new Point(x, 0), new Point(x, ActualHeight));
}
}
One solution is to create a custom Grid control to handle the width, height
public class SquareGrid : Grid
{
public SquareGrid()
{
this.SizeChanged += OnSizeChanged;
this.Loaded += OnLoaded;
}
private void OnSizeChanged(object sender, SizeChangedEventArgs e)
{
var parent = VisualTreeHelper.GetParent(this) as FrameworkElement;
if (parent == null) return;
ResizeToSquare(parent);
}
private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
{
var parent = VisualTreeHelper.GetParent(this) as FrameworkElement;
if (parent == null) return;
parent.SizeChanged += ParentOnSizeChanged;
}
private void ParentOnSizeChanged(object sender, SizeChangedEventArgs sizeChangedEventArgs)
{
FrameworkElement parent = sender as FrameworkElement;
if (parent == null) return;
ResizeToSquare(parent);
}
private void ResizeToSquare(FrameworkElement parent)
{
var min = Math.Min(parent.ActualHeight, parent.ActualWidth);
this.Width = min;
this.Height = min;
}
}
You could also build a Behavior for this that would do the same thing.
I am deriving from shape to draw an ellipse. The drawing starts at 0,0 so only the bottom right corner of the ellipse its drawn. How do I transform the origin in the overridegeometry method:
class Ellipse2 : Shape
{
EllipseGeometry ellipse;
public static readonly DependencyProperty TextBoxRProperty = DependencyProperty.Register("TextBoxR", typeof(TextBox), typeof(Ellipse2), new FrameworkPropertyMetadata(null));
public TextBox TextBox
{
get { return (TextBox)GetValue(TextBoxRProperty); }
set { SetValue(TextBoxRProperty, value); }
}
public Ellipse2()
{
ellipse = new EllipseGeometry();
this.Stroke = Brushes.Gray;
this.StrokeThickness = 3;
}
protected override Geometry DefiningGeometry
{
get
{
ellipse.RadiusX = this.Width/2;
ellipse.RadiusY = this.Height/2;
return ellipse;
}
}
}
I fixed it by using
protected override Geometry DefiningGeometry
{
get
{
TranslateTransform t = new TranslateTransform(ActualWidth / 2, ActualHeight / 2);
ellipse.Transform = t;
ellipse.RadiusX = this.ActualWidth/2;
ellipse.RadiusY = this.ActualHeight/2;
return ellipse;
}
}
Another way would be to set the center property of the ellipse I think to the attributes (I haven't tried this yet).
How can I animate the the scrolling for ListBox? I know I can use scrollIntoView but how can I animate it? I want to press the arrow keys to move from one listBoxItem to another.
Here is a rough implementation based on the same approach as the following link
http://aniscrollviewer.codeplex.com/
The VerticalOffset property is read-only so instead you can use an attached property VerticalOffset on the ScrollViewer which in turn does ScrollToVerticalOffset. This attached property can be animated.
You can also create an extension method for ItemsControl called AnimateScrollIntoView.
Call it like this
listBox.AnimateScrollIntoView(yourItem);
ScrollViewerBehavior
public class ScrollViewerBehavior
{
public static DependencyProperty VerticalOffsetProperty =
DependencyProperty.RegisterAttached("VerticalOffset",
typeof(double),
typeof(ScrollViewerBehavior),
new UIPropertyMetadata(0.0, OnVerticalOffsetChanged));
public static void SetVerticalOffset(FrameworkElement target, double value)
{
target.SetValue(VerticalOffsetProperty, value);
}
public static double GetVerticalOffset(FrameworkElement target)
{
return (double)target.GetValue(VerticalOffsetProperty);
}
private static void OnVerticalOffsetChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
{
ScrollViewer scrollViewer = target as ScrollViewer;
if (scrollViewer != null)
{
scrollViewer.ScrollToVerticalOffset((double)e.NewValue);
}
}
}
ItemsControlExtensions
public static class ItemsControlExtensions
{
public static void AnimateScrollIntoView(this ItemsControl itemsControl, object item)
{
ScrollViewer scrollViewer = VisualTreeHelpers.GetVisualChild<ScrollViewer>(itemsControl);
UIElement container = itemsControl.ItemContainerGenerator.ContainerFromItem(item) as UIElement;
int index = itemsControl.ItemContainerGenerator.IndexFromContainer(container);
double toValue = scrollViewer.ScrollableHeight * ((double)index / itemsControl.Items.Count);
Point relativePoint = container.TranslatePoint(new Point(0.0, 0.0), Window.GetWindow(container));
DoubleAnimation verticalAnimation = new DoubleAnimation();
verticalAnimation.From = scrollViewer.VerticalOffset;
verticalAnimation.To = toValue;
verticalAnimation.DecelerationRatio = .2;
verticalAnimation.Duration = new Duration(TimeSpan.FromMilliseconds(1000));
Storyboard storyboard = new Storyboard();
storyboard.Children.Add(verticalAnimation);
Storyboard.SetTarget(verticalAnimation, scrollViewer);
Storyboard.SetTargetProperty(verticalAnimation, new PropertyPath(ScrollViewerBehavior.VerticalOffsetProperty));
storyboard.Begin();
}
}
And since you also need to get a hold of the ScrollViewer you'll need this
public static class VisualTreeHelpers
{
public static T GetVisualChild<T>(DependencyObject parent) where T : Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
child = v as T;
if (child == null)
{
child = GetVisualChild<T>(v);
}
if (child != null)
{
break;
}
}
return child;
}
}
Take a look at this article, it explains how animate scrolling and add touch gestures. Download the source at the bottom of the page and look at WpfScrollContent solution. I would extend the WPF ListBox and add the scroll animation to it that way you can reuse the control.