我在 wpf 中准备了示例性的轮播。例如,您可能想使用 UserControl 形式的代码。正如您所建议的,我使用 StackPanel 准备了轮播。我的表单代码如下所示:
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Storyboard x:Key="CarouselStoryboard">
<DoubleAnimation
Storyboard.TargetName="CarouselTransform"
Storyboard.TargetProperty="X"/>
</Storyboard>
</Window.Resources>
<Canvas>
<StackPanel Name="Carousel" Orientation="Horizontal">
<StackPanel.RenderTransform>
<TranslateTransform x:Name="CarouselTransform" />
</StackPanel.RenderTransform>
<Button Height="350" Width="525" Content="Page1"/>
<Button Height="350" Width="525" Content="Page2"/>
<Button Height="350" Width="525" Content="Page3"/>
</StackPanel>
<Button Click="Left_Click" Content="Left" HorizontalAlignment="Left" Margin="10,164,0,0" VerticalAlignment="Top" Width="45">
</Button>
<Button Click="Right_Click" Content="Right" HorizontalAlignment="Left" Margin="448,170,0,0" VerticalAlignment="Top" Width="45"/>
</Canvas>
</Window>
WindowResources 中的 Storyboard 元素定义要执行的动画。它将更改应用于 StackPanel“Carousel”的 TranslationTransform 的 X 属性 - 这将导致该面板的动画移动。面板内的 3 个按钮模拟轮播的 3 个面板。底部有 2 个按钮 - 一个用于向左移动,第二个用于向右移动。有与它们绑定的回调方法。表单后面的代码如下所示:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private int currentElement = 0;
private void Left_Click(object sender, RoutedEventArgs e)
{
if(currentElement < 2)
{
currentElement++;
AnimateCarousel();
}
}
private void Right_Click(object sender, RoutedEventArgs e)
{
if (currentElement > 0)
{
currentElement--;
AnimateCarousel();
}
}
private void AnimateCarousel()
{
Storyboard storyboard = (this.Resources["CarouselStoryboard"] as Storyboard);
DoubleAnimation animation = storyboard.Children.First() as DoubleAnimation;
animation.To = -this.Width * currentElement;
storyboard.Begin();
}
}
currentElement 字段保存当前正在向用户显示哪个面板的信息。方法 AnimateCarousel 实际上启动了动画。它引用资源中定义的 Storyboard,并将其 DoubleAnimation To 属性设置为 Carousel 面板应移动到的值。然后通过调用情节提要上的 Begin 方法来执行动画。