[英]scroll viewer text block scrolling in WP7
我有一個綁定到滾動查看器的文本塊來滾動文本。 我希望文本在觸發按鈕點擊等事件時自動滾動而不顯示任何用戶輸入。 我嘗試使用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>
在代碼隱藏中,我添加了一個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);
}
}
現在,您可以將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();
}
當然,您也可以在xaml代碼中創建動畫,使其看起來更清晰。 現在,ScrollViewer的內容是固定的......您可以通過向包裝類添加更多依賴項屬性來使其更改。
我不知道這是不是最好的解決方案,事實上它對我來說看起來很難看,但它應該讓你知道如何做到這一點。
您需要為偏移設置動畫。 由於無法對偏移屬性進行動畫處理 - 您必須使用自己的動畫解決方案來更新每幀的偏移量,或者為每次更改時調用ScrollToVerticalOffset的偏移量創建附加的依賴項屬性,並且可以進行動畫處理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.