Mug*_*ugu 3 c# scrollviewer windows-phone-7
我有一个绑定到滚动查看器的文本块来滚动文本.我希望文本在触发按钮点击等事件时自动滚动而不显示任何用户输入.我尝试使用ScrollToVerticalOffset,但过渡并不顺利.无论如何,我可以使文本顺利向上滚动.
下面是一个示例,我创建了一个名为AnimatableScrollViewer的包装器控件,它包含一个常用的ScrollViewer和一个TextBlock.
<UserControl>
<Grid x:Name="LayoutRoot" Background="Transparent">
<ScrollViewer x:Name="scrollViewer" Width="{Binding ActualWidth, ElementName=userControl, Mode=OneWay}" Height="{Binding ActualHeight, ElementName=userControl, Mode=OneWay}">
<TextBlock TextWrapping="Wrap" Text="Add some pretty long text here..."/>
</ScrollViewer>
</Grid>
</UserControl>
Run Code Online (Sandbox Code Playgroud)
在代码隐藏中,我添加了一个DependencyProperty(我们可以从外部制作动画),在每次更改时调用ScrollViewer的ScrollToVerticalOffset()方法.
public partial class AnimatableScrollViewer : UserControl
{
public static readonly DependencyProperty AnimatablOffsetProperty = DependencyProperty.Register("AnimatableOffset",
typeof(double), typeof(AnimatableScrollViewer), new PropertyMetadata(AnimatableOffsetPropertyChanged));
public double AnimatableOffset
{
get { return (double)this.GetValue(AnimatablOffsetProperty); }
set { this.SetValue(AnimatablOffsetProperty, value); }
}
public AnimatableScrollViewer()
{
InitializeComponent();
AnimatableOffset = scrollViewer.VerticalOffset;
}
private static void AnimatableOffsetPropertyChanged(object sender, DependencyPropertyChangedEventArgs args)
{
AnimatableScrollViewer cThis = sender as AnimatableScrollViewer;
cThis.scrollViewer.ScrollToVerticalOffset((double)args.NewValue);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以将AnimatableScrollViewer添加到PhonePage并为其设置动画.例如,在像这样的按钮事件处理程序中:
private void cmdScroll_Click(object sender, RoutedEventArgs e)
{
// Calculate target offset
double targetOffset = 1000;
// Create animation and storyboard
DoubleAnimation animation = new DoubleAnimation();
animation.EasingFunction = new CircleEase();
animation.Duration = new Duration(new TimeSpan(0, 0, 2));
animation.From = animatableScrollViewer.AnimatableOffset;
animation.To = targetOffset;
Storyboard.SetTarget(animation, animatableScrollViewer);
Storyboard.SetTargetProperty(animation, new PropertyPath("(AnimatableScrollViewer.AnimatableOffset)"));
Storyboard storyboard = new Storyboard();
storyboard.Children.Add(animation);
storyboard.Begin();
}
Run Code Online (Sandbox Code Playgroud)
当然,您也可以在xaml代码中创建动画,使其看起来更清晰.现在,ScrollViewer的内容是固定的......您可以通过向包装类添加更多依赖项属性来使其更改.
我不知道这是不是最好的解决方案,事实上它对我来说看起来很难看,但它应该让你知道如何做到这一点.