XAML
<Grid>
<!-- 滚动条背景 -->
<Rectangle
x:Name="BackgroundRect"
Width="400" Height="14"
Fill="LightGray" />
<!-- 滑轨的滑块, 使用 2 个 path 相交得到一个滑块, 然后移动第二个滑块的位置,得到一个运行的滑块动画 -->
<Path
x:Name="SlideRailPath"
Width="{Binding ElementName=BackgroundRect, Path=ActualWidth}"
Height="{Binding ElementName=BackgroundRect, Path=ActualHeight}"
Fill="CornflowerBlue">
<Path.Triggers>
<EventTrigger RoutedEvent="Loaded">
<BeginStoryboard>
<Storyboard>
<!-- 动画调整滑块的 x 值 -->
<DoubleAnimation
RepeatBehavior="Forever"
Storyboard.TargetName="SliderTransform" Storyboard.TargetProperty="X" From="-50"
To="{Binding ElementName=SlideRailPath, Path=ActualWidth}"
Duration="0:0:5" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Path.Triggers>
<Path.Data>
<!-- 两个相交的矩形得到一个方块, Intersect 指定相交有效 -->
<CombinedGeometry GeometryCombineMode="Intersect">
<CombinedGeometry.Geometry1>
<RectangleGeometry>
<RectangleGeometry.Rect>
<!-- 自动计算方块的大小, 与轨道一致大小 -->
<MultiBinding Converter="{StaticResource RectWithParentSizeValueConverter}">
<Binding ElementName="SlideRailPath" Path="ActualWidth" />
<Binding ElementName="SlideRailPath" Path="ActualHeight" />
</MultiBinding>
</RectangleGeometry.Rect>
</RectangleGeometry>
</CombinedGeometry.Geometry1>
<CombinedGeometry.Geometry2>
<!-- 滑块的大小, 设置 x 值为 Transform 值,可以使用动画调整 -->
<RectangleGeometry Rect="0 0 50 14">
<RectangleGeometry.Transform>
<TranslateTransform x:Name="SliderTransform" X="50" />
</RectangleGeometry.Transform>
</RectangleGeometry>
</CombinedGeometry.Geometry2>
</CombinedGeometry>
</Path.Data>
</Path>
</Grid>