我用 C# 为 WP7 编写了这段代码:
public void btn_handler(object sender, EventArgs args)
{
Button btn_Pressed = (Button)sender;
ImageBrush br = new ImageBrush();
br.ImageSource = new BitmapImage(new Uri("/images/cat.png"
, UriKind.Relative));
btn_Pressed.Background = br;
Thread.Sleep(5000);
SolidColorBrush sBrush = new SolidColorBrush();
sBrush.Color = System.Windows.Media.Colors.White;
btn_Pressed.Background = sBrush;
}
每当用户单击按钮时,我希望按钮的背景更改为图像。大约 5 秒后,我希望背景变回白色。目前,程序不会改变按钮的背景图片,而是等待5秒,直接将背景改为白色。
我是 WP 的菜鸟。我尝试寻找解决方案,得到的是创建一个调度程序线程,但我不明白如何继续。请帮忙 :(
您当前的方法是不正确的。它让 UI 线程变得忙碌。它会在空闲时更新 UI。
这是正在发生的事情
按钮获得点击。 UI 线程将按钮背景更改为图像。然后它会休眠 5 秒,然后将背景更改为白色。请注意,UI 线程仍然繁忙。它只会在免费时更新实际的 UI。一旦它将背景颜色更改为白色,它就会释放并更新 UI,您会在屏幕上看到更改。
你需要这样做
//inside the button click event create a background worker
BackgroundWorker worker = new BackgroundWorker();
worker.RunWorkerCompleted += new
RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerAsync();
Button btn_Pressed = (Button)sender;
ImageBrush br = new ImageBrush();
br.ImageSource = new BitmapImage(new Uri("/images/cat.png", UriKind.Relative));
btn_Pressed.Background = br;
public static void worker_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
//once backgroudn work i.e. DoWork is complete this method will be
//called and code below will execute in UI thread
SolidColorBrush sBrush = new SolidColorBrush();
sBrush.Color = System.Windows.Media.Colors.White;
btn_Pressed.Background = sBrush;
}
public static void worker_DoWork(object sender, DoWorkEventArgs e)
{
//it will wait 5 secs in the background thread
Thread.Sleep(5000);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)