我有一个应用程序,在加载窗口时会占用大量时间。
在Window_load事件中,我从数据库中读取了某些控件的状态和名称。
我想做一个初始屏幕,该窗口将在窗口完全加载后结束。
我已经尝试过使用http://www.codeproject.com/KB/dialog/wpf_animated_text_splash.aspx这个示例,但是在主窗口完全加载之前关闭了启动屏幕,我的主窗口显示为白色且未完全加载。
我是wpf的初学者,但我不知道如何在初始窗口完全加载之前将初始屏幕保留在屏幕上。
请给我一个例子。
我的启动画面代码:
public partial class SplashWindow : Window
{
Thread loadingThread;
Storyboard Showboard;
Storyboard Hideboard;
private delegate void ShowDelegate(string txt);
private delegate void HideDelegate();
ShowDelegate showDelegate;
HideDelegate hideDelegate;
public SplashWindow()
{
InitializeComponent();
showDelegate = new ShowDelegate(this.showText);
hideDelegate = new HideDelegate(this.hideText);
Showboard = this.Resources["showStoryBoard"] as Storyboard;
Hideboard = this.Resources["HideStoryBoard"] as Storyboard;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
loadingThread = new Thread(load);
loadingThread.Start();
}
private void load()
{
Thread.Sleep(6000);
this.Dispatcher.Invoke(showDelegate, "first data to loading");
Thread.Sleep(6000);
//load data
this.Dispatcher.Invoke(hideDelegate);
Thread.Sleep(6000);
this.Dispatcher.Invoke(showDelegate, "second data loading");
Thread.Sleep(6000);
//load data
this.Dispatcher.Invoke(hideDelegate);
Thread.Sleep(6000);
this.Dispatcher.Invoke(showDelegate, "last data loading");
Thread.Sleep(6000);
//load data
this.Dispatcher.Invoke(hideDelegate);
//close the window
Thread.Sleep(6000);
this.Dispatcher.Invoke(DispatcherPriority.Normal,(Action)delegate() { Close(); });
}
private void showText(string txt)
{
txtLoading.Text = txt;
BeginStoryboard(Showboard);
}
private void hideText()
{
BeginStoryboard(Hideboard);
}
}
我将在MainWindow构造函数中调用此初始屏幕:
new SplashWindow().ShowDialog();
但是我的MainWindow Load函数将在“启动窗口”完成显示后运行。
谢谢!
最佳答案
如果使用内置的 SplashScreen
类,则可以调用 Show(false)
来指定您将负责关闭初始屏幕。然后,您可以使用 Close()
方法将其关闭。
请注意,SplashScreen
类仅支持显示静态图像。它这样做的理由非常充分-尽快将启动屏幕显示在用户面前。
代码看起来像这样:
static class Entry
{
static void Main(string[] args)
{
var splashScreen = new SplashScreen("path/to/your/image.png");
splashScreen.Show(false);
InitializeLogging();
InitializeServices();
InitializeUserInterface();
InitializeWhateverElseYouNeed();
splashScreen.Close(TimeSpan.FromSeconds(1));
}
}
关于WPF启动画面,直到Windows结束加载,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6121892/