我有一个 WPF 应用程序,它会在单击按钮时设置图像源 我想在这么多秒后清除图像源,比如 15 秒过去了。 我怎样才能做到这一点? 我曾尝试使用 Thread.sleep,但它会立即清除源代码,然后将应用程序暂停 15 秒
这是我的方法
private void btnCapture_Click(object sender, RoutedEventArgs e)
{
imgCapture.Source = //my image source;
Thread.Sleep(15000);
imgCapture.Source = null;
}
我也试过
private void btnCapture_Click(object sender, RoutedEventArgs e)
{
imgCapture.Source = //my image source;
imgCapture.Source = null;
Thread thread = new Thread(new ThreadStart(clearSource));
thread.Start();
}
private void clearSource()
{
Thread.Sleep(15000);
imgCapture.Source = null;
}
但我收到一条错误消息,提示调用线程无法访问此对象,因为另一个线程拥有它。
如何在 15 秒后清除该图像源。
谢谢!
最佳答案
使用 DispatcherTimer :
DispatcherTimer timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(15) };
// in constructor
timer.Tick += OnTimerTick;
private void btnCapture_Click(object sender, RoutedEventArgs e)
{
imgCapture.Source = //my image source;
timer.Start();
}
private void OnTimerTick(object sender, EventArgs e)
{
timer.Stop();
imgCapture.Source = null;
}
关于wpf - x 秒后删除图像源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14510982/