在WPF应用程序中更改Button的BackgroundImage

时间:2016-03-12 02:50:59

标签: c# wpf multithreading background-image dispatcher

在我的c#app中,我试图更改按钮的背景图像并在几秒钟后将其更改回来。但是,直到计时器启动后才会更改背景图像,然后在您看到更改之前立即将其更改回原始图像。

private void button1_Click(object sender, EventArgs e)
{
    myImage.BackgroundImage = Properties.Resources.newImage;
    System.Threading.Thread.Sleep(5000);
    myImage.BackgroundImage = Properties.Resources.myImage;
}

1 个答案:

答案 0 :(得分:1)

假设这是一个WPF应用,请添加DispatcherTimer,如以下代码段所示:

DispatcherTimer _dispatcherTimer = new DispatcherTimer();
public MainWindow()
{
    InitializeComponent();
    button1.Click += button1_Click;
    _dispatcherTimer.Tick += new EventHandler(dt_Tick);
    _dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 5);
}

private void button1_Click(object sender, RoutedEventArgs e)
{
    myImage.BackgroundImage = Properties.Resources.newImage;
    _dispatcherTimer.Start();
}

void dt_Tick(object sender, EventArgs e)
{
    _dispatcherTimer.Stop();
    myImage.BackgroundImage = Properties.Resources.myImage;
}

希望这会有所帮助。