wpf 如何等待表单加载,然后启动方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12321138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to wait for form to load, then start method?
提问by user1588364
I have a WPF application that on load executes a method that checks if certain files exist, and if not, downloads them. It also downloads a string to be used as a message, and outputs to an in-appconsole.
我有一个 WPF 应用程序,它在加载时执行一个方法,该方法检查某些文件是否存在,如果不存在,则下载它们。它还下载用作消息的字符串,并输出到in-app控制台。
However, when I launch the program I see a white screen for a few seconds, then the window loads and everything is done. So it appears that the method is being executed before the window loads.
但是,当我启动程序时,我看到白屏几秒钟,然后窗口加载,一切都完成了。因此,该方法似乎是在窗口加载之前执行的。
How can I wait for the window to load, wait about 2 seconds, then run the method?
如何等待窗口加载,等待大约 2 秒,然后运行该方法?
This is the code of the method i am trying to run:
这是我尝试运行的方法的代码:
consolemessage("STARTUP", "Verifying existence of essential files...");
if(!File.Exists("Interop.NATUPNPLib.dll"))
Download("link here", "Interop.NATUPNPLib.dll");
if(!File.Exists("LICENSE.txt"))
Download("link here", "LICENSE.txt");
consolemessage("STARTUP", "Essential file validation completed!");
回答by Trevor Elliott
If you see a white screen for a few seconds, it means your task (downloading the files) is taking a few seconds. You could start this task after your window loads by subscribing to the "Loaded" event of your window, but it's still going to freeze the application for 3 seconds.
如果您看到几秒钟的白屏,则表示您的任务(下载文件)需要几秒钟。您可以在窗口加载后通过订阅窗口的“Loaded”事件来启动此任务,但它仍会使应用程序冻结 3 秒钟。
You have to a create a solution that fits your needs for how to handle this task in a user friendly way.
您必须创建一个解决方案,以满足您如何以用户友好的方式处理此任务的需求。
If you want to block the user from using the application before this information is retrieved, you can create a popup with a loading animation or a progress bar. You can animate these as your task is given time to complete.
如果您想在检索此信息之前阻止用户使用该应用程序,您可以创建一个带有加载动画或进度条的弹出窗口。当您的任务有时间完成时,您可以为这些设置动画。
If you want the user to be able to use your application while the information is loaded in the background, you need to use something like a BackgroundWorker or other asynchronous design to load the information on another thread, then callback the main thread when the information is ready and loaded. If you're using web requests, you can often just turn them into asynchronous web requests by using the asynchronous overloads such as "BeginGetResponse". It depends on your code.
如果你想让用户在后台加载信息的同时也可以使用你的应用,你需要使用BackgroundWorker之类的东西或者其他异步设计来加载另一个线程上的信息,然后在信息加载时回调主线程准备好并加载。如果您正在使用 Web 请求,您通常可以通过使用诸如“BeginGetResponse”之类的异步重载将它们转换为异步 Web 请求。这取决于您的代码。
EDIT:
编辑:
You could create the BackgroundWorker in the scope of your Window like so:
您可以像这样在 Window 范围内创建 BackgroundWorker:
public partial class MainWindow : Window
{
private BackgroundWorker worker;
public MainWindow()
{
InitializeComponent();
Loaded += MainWindow_Loaded;
}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
worker = new BackgroundWorker();
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
worker.RunWorkerAsync();
consolemessage("STARTUP", "Verifying existence of essential files...");
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
if (!File.Exists("Interop.NATUPNPLib.dll"))
Download("link here", "Interop.NATUPNPLib.dll");
if (!File.Exists("LICENSE.txt"))
Download("link here", "LICENSE.txt");
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// Signal your UI that the files are now available here if needed.
consolemessage("STARTUP", "Essential file validation completed!");
}
}
回答by Mark Hall
You could also initiate a one shot timer in your Form.LoadedEvent with a 100 millisecond delay or so, then run your method in it. That is what I have done in the past to allow the Form to fully load before I run my Code.
您还可以在您的Form.LoadedEvent 中启动一个单次计时器,延迟 100 毫秒左右,然后在其中运行您的方法。这就是我过去所做的,以便在运行我的代码之前让表单完全加载。
example:
例子:
public partial class MainWindow : Window
{
System.Windows.Threading.DispatcherTimer oneShot = new System.Windows.Threading.DispatcherTimer();
public MainWindow()
{
InitializeComponent();
oneShot.Interval = new TimeSpan(0, 0, 0, 0, 100);
oneShot.Tick += new EventHandler(oneShot_Tick);
}
void oneShot_Tick(object sender, EventArgs e)
{
oneShot.Stop();
// Your Code or Method here
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
oneShot.Start();
}
}
回答by Kevin DiTraglia
You could place the code in the Window_Loadedevent. Here is a quick and dirty implementation that won't freeze your UI (just keep in mind if the user can do something that attempts to reference these things before they are actually complete it could throw an exception, in which case use Moozhe's solution to create a loading screen of some kind)
您可以将代码放在Window_Loaded事件中。这是一个快速而肮脏的实现,不会冻结您的 UI(请记住,如果用户可以在实际完成之前尝试引用这些内容,则可能会引发异常,在这种情况下,请使用 Moozhe 的解决方案来创建某种加载屏幕)
Using at top:
在顶部使用:
using System.Threading;
simple code:
简单代码:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Thread t = new Thread( YourMethod);
t.IsBackground = true;
t.Start();
}
void YourMethod()
{
consolemessage("STARTUP", "Verifying existence of essential files...");
if (!File.Exists("Interop.NATUPNPLib.dll"))
Download("link here", "Interop.NATUPNPLib.dll");
if (!File.Exists("LICENSE.txt"))
Download("link here", "LICENSE.txt");
consolemessage("STARTUP", "Essential file validation completed!");
}

