我想顯示窗口,但出現錯誤「調用線程必須是STA,因爲很多UI組件都需要這個」。我發現了這種溶劑,但每次寫這個都很困難。WPF與STA線程錯誤的靈活性
Application.Current.Dispatcher.Invoke((Action) delegate
{
msgBox =
new CustomMessageBox(
"Файл добавлен в базу, строки " + errors +
" не были добавлены по причине неверных входных данных",
"Уведомление");
msgBox.Show();
});
是否還有其他解決方案?我把CustomMessageBoxBelow
public partial class CustomMessageBox : Window
{
public CustomMessageBox()
{
InitializeComponent();
}
public CustomMessageBox(string text, string title)
{
InitializeComponent();
Title = title;
TextBlock.Text = text;
}
private void OkBtn_OnClick(object sender, RoutedEventArgs e)
{
this.Close();
}
}
顯示消息框在輔助線程是很少是個好主意,這被認爲是可怕的。如果它不是很糟糕,那麼幾乎每個人都會錯誤的。改爲使用BackgroundWorker或TaskScheduler.FromCurrentSynchronizationContext()。 –
你在主要方法中有'STAThread'屬性嗎? – Valentin