【发布时间】:2012-01-29 15:58:05
【问题描述】:
我正在寻找使用 C# 创建一个 Windows Phone 应用程序。我想要一个计时器,它显示一个图像 100 毫秒,然后切换到另一个图像,然后再等待 900 毫秒,然后再次闪烁图像。我写了下面的代码,但是,它似乎并没有持续闪烁。有什么想法吗?
public partial class MainPage : PhoneApplicationPage
{
DispatcherTimer timer = new DispatcherTimer();
List<string> files = new List<string>() { "Images/off-light.png", "Images/on-light.png" };
List<BitmapImage> images = new List<BitmapImage>();
int current = 0;
// Constructor
public MainPage()
{
InitializeComponent();
foreach (string file in files)
{
BitmapImage image = new BitmapImage(new Uri(file, UriKind.Relative));
images.Add(image);
}
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(900);
timer.Tick += new EventHandler(timer_Tick);
}
void timer_Tick(object sender, EventArgs e)
{
myImage.Source = images[current];
current++;
if (current >= files.Count)
{
current = 0;
timer.Interval = TimeSpan.FromMilliseconds(100);
timer.Stop();
timer.Start();
}
else
{
timer.Interval = TimeSpan.FromMilliseconds(900);
timer.Stop();
timer.Start();
}
}
private void btnStop_Click(object sender, RoutedEventArgs e)
{
timer.Stop();
myImage.Source = images[0];
}
private void btnStart_Click(object sender, RoutedEventArgs e)
{
timer.Start();
}
}
【问题讨论】:
-
在这种情况下“不一致”是什么意思?图像是否闪烁一次,然后不再闪烁?它的停留时间是长于还是短于 100 毫秒?此外,您可能会考虑更改操作顺序。停止计时器,设置间隔,然后重新启动计时器。虽然说实话,我认为你可以只设置间隔而不停止/重新启动。
-
不一致,因为图像显示的时间不是真正的 100 毫秒,也不是每次都真正等待 900 毫秒。我将尝试设置间隔而不停止和重新启动。
-
当我在这段代码中放一行来播放点击类型的 mp3 文件时,我真正注意到的地方是: if (current >= files.Count) { current = 0; timer.Interval = TimeSpan.FromMilliseconds(100);计时器.停止();计时器.Start();我有时会连续多次听到“咔哒”声,有时只听到一次。但绝对不一致。听起来好像有多个计时器。
标签: c# windows-phone-7 timer intervals