下面是一个快速而肮脏的滚动控件的代码,一旦用户将鼠标悬停在控件上,它就会执行您想要的操作。
<Canvas Name="brd"
ClipToBounds="True"
Margin="10"
Height="20" Width="150"
Background="White"
HorizontalAlignment="Left">
<StackPanel Name="spl1"
Orientation="Horizontal"
Canvas.Left="0">
<TextBlock Name="tbk1"
Margin="10,0"
MinWidth="{Binding ElementName=brd,Path=ActualWidth}"
Text="A display of test text that is wider than the control."/>
<TextBlock MinWidth="{Binding ElementName=brd,Path=ActualWidth}"
Margin="10,0"
Text="{Binding ElementName=tbk1,Path=Text}"/>
</StackPanel>
<Canvas.Triggers>
<EventTrigger RoutedEvent="MouseEnter">
<BeginStoryboard Name="scroll">
<Storyboard RepeatBehavior="Forever">
<DoubleAnimation To="-200" Duration="0:0:4"
Storyboard.TargetName="spl1"
Storyboard.TargetProperty="(Canvas.Left)" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
<EventTrigger RoutedEvent="MouseLeave">
<StopStoryboard BeginStoryboardName="scroll"/>
</EventTrigger>
</Canvas.Triggers>
</Canvas>
为了正确操作,您需要更改一个部分,但我没有实施。<DoubleAnimation To="-200"...
遗嘱需要改变。理想情况下,for 的值To
将是控件ActualWidth
属性的负值。tbk1
这将需要一个元素绑定来获取值和一个ValueConverter
使该值成为负值。
如果您不想麻烦使用转换器,您可以使该To
值足够大以容纳您期望的最长文本。这会让你相当接近。
当然,您可以对此进行更多调整,以在一个动画周期结束和下一个动画周期开始时提供更平滑的过渡。
编辑
好吧,我不能让它完成一半。下面是更新后的 XAML 以实现流畅操作,以及包含的ValueConverter
.
<Window.Resources>
<Converters:ChangeSignConverter x:Key="ChangeSignConverter"/>
</Window.Resources>
<Canvas Name="brd"
ClipToBounds="True"
Margin="10"
Height="20" Width="150"
Background="White"
HorizontalAlignment="Left">
<StackPanel Name="spl1"
Margin="5,0,0,0"
Orientation="Horizontal"
Canvas.Left="0">
<TextBlock Name="tbk1"
Padding="0,0,10,0"
MinWidth="{Binding ElementName=brd,Path=ActualWidth}"
Text="A display of test text that is wider than the control."/>
<TextBlock MinWidth="{Binding ElementName=brd,Path=ActualWidth}"
Text="{Binding ElementName=tbk1,Path=Text}"/>
</StackPanel>
<Canvas.Triggers>
<EventTrigger RoutedEvent="MouseEnter">
<BeginStoryboard Name="scroll">
<Storyboard RepeatBehavior="Forever">
<DoubleAnimation To="{Binding ElementName=tbk1,Path=ActualWidth,Converter={StaticResource ChangeSignConverter}}"
Duration="0:0:4"
Storyboard.TargetName="spl1"
Storyboard.TargetProperty="(Canvas.Left)" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
<EventTrigger RoutedEvent="MouseLeave">
<StopStoryboard BeginStoryboardName="scroll"/>
</EventTrigger>
</Canvas.Triggers>
</Canvas>
转换器类:
class ChangeSignConverter : IValueConverter
{
object IValueConverter.Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return Convert.ToDouble(value) * -1;
}
object IValueConverter.ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return Convert.ToDouble(value) * -1;
}
}