我在C#中有一个WPF应用程序。当有人触摸图像(image1)时,我希望更改图像(image2),延迟2秒,最后更改为image3。
我的代码如下:
private void ImageName_TouchDown(object sender, TouchEventArgs e)
{
BitmapImage image = new BitmapImage(new Uri("c:/3.jpg", UriKind.Absolute));
ImageName.Source =image;
Thread.Sleep(2000);
image = new BitmapImage(new Uri("c:/4.jpg", UriKind.Absolute));
ImageName.Source = image;
}
我有延迟工作,但似乎像c#仅更新image3(4.jpg)。就像它无法更新事件处理程序中的图像源。我该怎么办?
非常感谢ROI
您可以使事件处理程序异步,并使用Task.Delay
而不是Thread.Sleep
:
private async void ImageName_TouchDown(object sender, TouchEventArgs e)
{
BitmapImage image = new BitmapImage(new Uri("c:/3.jpg", UriKind.Absolute));
ImageName.Source =image;
await Task.Delay(2000);
image = new BitmapImage(new Uri("c:/4.jpg", UriKind.Absolute));
ImageName.Source = image;
}
时间延迟和图像更新处理应在与主UI线程不同的位置上执行:
private void ImageName_TouchDown(object sender, TouchEventArgs e)
{
BitmapImage image = new BitmapImage(new Uri("c:/3.jpg", UriKind.Absolute));
ImageName.Source =image;
System.Threading.Thread thread = new System.Threading.Thread(
delegate() {
Thread.Sleep(2000);
Dispatcher.BeginInvoke(new Action(() => {
image = new BitmapImage(new Uri("c:/4.jpg", UriKind.Absolute));
ImageName.Source = image;
}), DispatcherPriority.SystemIdle);
}
);
thread.Start();
}