c# - 如何更改图像源,在 GUI 中显示并在之后运行一些代码?
问题描述
我的 WPF 中有一个图像控件(基本上是整个窗口)。当用户输入错误时,我希望图像更改甚至摇动屏幕,等待一秒钟(使用 Thread.Sleep())然后将图像更改回原始图像。
问题是:即使我在摇动屏幕之前更改了函数中的图像,但在执行所有函数后它仍然会发生变化。
我怎样才能实现我的目标?
这是我尝试过的:
//Change Diary Background
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = new Uri(System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName) + @"\lib\ViewLogin\ViewLoginIncorrect.png");
bitmap.EndInit();
imgDiary.Source = bitmap;
Thread.Sleep(1000);
//Shake Screen
this.Left = this.Left - 20;
Thread.Sleep(50);
this.Left = this.Left + 20;
txtMasterKey.Focus();
只有在一切都完成后,我的形象才会改变。 图片示例
解决方案
Thread.sleep 阻塞了 ui 线程,该线程会改变任何 ui
那是你的问题。
使您的方法异步。
将 thread.sleep(n) 替换为 await task.delay(n)。
其中 n 是您那里的数字。
推荐阅读
- c# - 如何将日期时间四舍五入到最接近的第 200 毫秒?
- c - 在多个结构指针和数组中为结构指针的成员赋值
- android - 报警意图进入快速无限循环
- apache-spark - S3 上的 Parquet 文件格式:哪个是实际的 Parquet 文件?
- python - 求解带阶跃函数的微分方程
- jquery - div 在从顶部以设置的像素数滚动后变为固定,也仅大于设置的窗口宽度,并添加了边框底部
- qnx - 致命:使用 mkxfs 的文件系统溢出错误
- php - 来自变量的Wordpress过滤器?
- python-3.x - 如何显示相距 15 分钟的记录的频率
- azure-devops - VSTS Publish Artifact 为空,MVC Web 应用程序在本地部署