我想知道是否有一种方法可以在 UWP 中创建自动旋转的图像轮播,每隔几秒就会更改背景图像。我尝试过使用 FlipView,但我注意到无法让它自动旋转图像。有办法做到这一点吗?
这是我尝试过的,但是在这种方法中,我必须单击箭头才能更改为下一张图像:
<DataTemplate x:Key="BackgroundImages">
<FlipView>
<Image Source="ms-appx:///Assets/Image1.png"></Image>
<Image Source="ms-appx:///Assets/Image2.png"></Image>
</FlipView>
</DataTemplate>
推荐使用Carousel控件,代表一个漂亮流畅的轮播,也可以使用FlipView。
在 UWP 中创建自动旋转的图像轮播?
我们可以使用DispatcherTimer定期修改当前的SelectedIndex,用于Carousel控件或FlipView。
//xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
<Grid>
<controls:Carousel x:Name="CarouselControl" InvertPositive="True" ItemDepth="300"
ItemMargin="0" ItemRotationX="0"
ItemRotationY="0" ItemRotationZ="0"
TransitionDuration="500"
Orientation="Horizontal">
<controls:Carousel.EasingFunction>
<CubicEase EasingMode="EaseOut" />
</controls:Carousel.EasingFunction>
<controls:Carousel.ItemTemplate>
<DataTemplate>
<Image Width="200"
Height="200"
VerticalAlignment="Bottom"
Source="{Binding}"
Stretch="Uniform" />
</DataTemplate>
</controls:Carousel.ItemTemplate>
</controls:Carousel>
</Grid>
public sealed partial class MainPage : Page
{
DispatcherTimer dispatcherTimer;
ObservableCollection<string> imgPath=new ObservableCollection<string>();
public MainPage()
{
this.InitializeComponent();
imgPath.Add("ms-appx:///Assets/OIP.jpg");
imgPath.Add("ms-appx:///Assets/OIP.jpg");
imgPath.Add("ms-appx:///Assets/OIP.jpg");
imgPath.Add("ms-appx:///Assets/OIP.jpg");
imgPath.Add("ms-appx:///Assets/OIP.jpg");
imgPath.Add("ms-appx:///Assets/OIP.jpg");
CarouselControl.ItemsSource = imgPath;
DispatcherTimerSetup();
}
public void DispatcherTimerSetup()
{
dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += dispatcherTimer_Tick;
dispatcherTimer.Interval = new TimeSpan(0, 0, 2);
dispatcherTimer.Start();
}
public int count = 0;
public void dispatcherTimer_Tick(object sender, object e)
{
count++;
if (imgPath.Count > 0)
{
CarouselControl.SelectedIndex = count % imgPath.Count;
}
}
}