原文:
WPF 超长文本的来回滚动
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Vblegend_2013/article/details/83621303
当较小的地方显示超长的文本时 实现左右来回滚动
引入命名空间
xmlns:Utility="clr-namespace:Test.Wpf.Utility"
实现
<ScrollViewer Name="slv"
IsHitTestVisible="False"
Background="#05FFFFFF"
Margin="2,10,2,0"
VerticalScrollBarVisibility="Hidden"
HorizontalScrollBarVisibility="Hidden">
<Label Content="{Binding Title, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
FontSize="18"
FontFamily="Microsoft YaHei"
Foreground="#FFFFFFFF"
Margin="5,0,5,0">
<Label.Triggers>
<EventTrigger RoutedEvent="Label.Loaded">
<BeginStoryboard HandoffBehavior="Compose">
<Storyboard>
<DoubleAnimation From="0"
To="{Binding ElementName=slv,Path=ScrollableWidth}"
Duration="0:0:2"
Storyboard.TargetName="slv"
AutoReverse="True"
RepeatBehavior="Forever"
BeginTime="0:0:0.2"
Storyboard.TargetProperty="(Utility:ScrollViewerBehavior.HorizontalOffset)">
</DoubleAnimation>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Label.Triggers>
</Label>
</ScrollViewer>
ScrollViewerBehavior类
using System.Windows;
using System.Windows.Controls;
namespace Test.Wpf.Utility
{
public static class ScrollViewerBehavior
{
public static readonly DependencyProperty HorizontalOffsetProperty = DependencyProperty.RegisterAttached("HorizontalOffset", typeof(double), typeof(ScrollViewerBehavior), new UIPropertyMetadata(0.0, OnHorizontalOffsetChanged));
public static void SetHorizontalOffset(FrameworkElement target, double value)
{
target.SetValue(HorizontalOffsetProperty, value);
}
public static double GetHorizontalOffset(FrameworkElement target)
{
return (double)target.GetValue(HorizontalOffsetProperty);
}
private static void OnHorizontalOffsetChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
{
var view = target as ScrollViewer;
if (view != null)
{
view.ScrollToHorizontalOffset((double)e.NewValue);
}
}
public static readonly 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)
{
var view = target as ScrollViewer;
if (view != null)
{
view.ScrollToVerticalOffset((double)e.NewValue);
}
}
}
}