3

我有一个 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 秒后清除该图像源。谢谢!

4

2 回答 2

4

使用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;
}
于 2013-01-24T21:29:40.060 回答
0

@Clemens 的回答很好,但为了满足我最近的RX恋物癖:

void btnCapture_Click(object sender, RoutedEventArgs e)
{
    imgCapture.Source = //my image source;
    Observable.Interval( TimeSpan.FromSeconds( 15 ) ).TimeInterval().Subscribe( _ => imgCapture.Source = null );
}
于 2013-01-24T21:59:20.050 回答