首页 > 解决方案 > 如何更改图像源,在 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();

只有在一切都完成后,我的形象才会改变。 图片示例

标签: c#wpfmultithreadingimageuser-interface

解决方案


Thread.sleep 阻塞了 ui 线程,该线程会改变任何 ui

那是你的问题。

使您的方法异步。

将 thread.sleep(n) 替换为 await task.delay(n)。

其中 n 是您那里的数字。


推荐阅读