【问题标题】:Why does my SplashScreen Not show a Label (Text)为什么我的 SplashScreen 不显示标签(文本)
【发布时间】:2015-05-04 19:00:23
【问题描述】:

我有一个名为SpalshScreen.csWinForm 带有一个简单标签,其中Text 属性设置为“数据加载...”。标签在表单中居中。我还定义了一个名为DoClose() 的公共方法。

我的MainForm.Form_Load 方法包含:

Hide();
SplashScreen form = new SplashScreen();
form.Show();

// Simulate Doing Database Table Load(s)
Thread.Sleep(5000);

form.DoClose();
Show();

但是,当我运行时,我的 Splash 确实出现了,但是,假设标签文本是它只显示一个浅色框。

如果我将form.Show(); 更改为form.ShowDialog();,文本会正确显示,但主循环会暂停,直到我关闭启动窗口。

【问题讨论】:

  • 在非 UI 线程中加载数据库,而不是在 UI 线程中。
  • 不,它们都加载到 UI 线程中。
  • 这不是一个问题,而是一个建议。
  • @Randy 是的。这就是您的代码不起作用的原因。不要那样做。
  • 好的。警告这对我来说将是一个愚蠢的问题,你的意思是做一个 context.Table.LoadAsync(); ?

标签: c# winforms splash-screen


【解决方案1】:

经过一系列的反复试验......诀窍是不要像@Servy 所说的那样阻塞 UI 线程。

Form_Load 方法需要更改为:

Hide();
Splash.Show();

// Everything after this line must be Non UI Thread Blocking
Task task = new Task(LoadDataAsync);
task.Start();
task.Wait();

Splash.DoClose();
Show();

我创建了一个 LoadDataAsync 方法来处理其他所有事情:

    private async void LoadDataAsync()
    {
        await Context.Employees.LoadAsync();
        await Context.Customers.LoadAsync();

        // The Invoke/Action Wrapper Keeps Modification of UI Elements from
        // complaining about what thread they are on.
        if (EmployeeDataGridView.InvokeRequired)
        {
            Action act = () => EmployeeBindingSource.DataSource = Context.Employees.Local.ToBindingList();
            EmployeeDataGridView.Invoke(act);
        }

        if (CustomerComboBox.InvokeRequired)
        {
            Action act = () =>
            {
                CustomerBindingSource.DataSource = GetCustomerList();
                CustomerComboBox.SelectedIndex = -1;
            };
            CustomerComboBox.Invoke(act);
        }
    }

我还将我使用的任何私有字段和私有方法设置为静态。

【讨论】:

    【解决方案2】:

    在启动画面表单中使用计时器而不是 thread.sleep(例如 5 秒后关闭启动画面),并设置它的关闭事件。

    var form = new SplashScreen();
    form.Closed += (s,e)=>{
        Show();
    }
    form.Show();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-17
      • 1970-01-01
      • 2021-01-23
      • 1970-01-01
      相关资源
      最近更新 更多