[英]Errors in VisualStudio when opening UserControl in designer
背景 :我已經創建了這個UserControl。 在用戶控件的構造函數中,我調用一個函數,該函數從數據庫中檢索一些值。 如果在檢索值時發生錯誤,則會顯示一個說明錯誤的消息框。 到現在為止還挺好。
問題:我創建了一個表單(其中包括其他元素)包括我的UserControl。 現在,當我打開此表單(甚至UserControl本身)時,將調用構造函數(我想這樣可以准確地繪制它),並且由於數據庫不可用,因此顯示了消息框(上面解釋了)。
如何防止這種情況發生?
我只想清楚:代碼在運行時效果很好。 一切都按設計。 僅在發生問題的Visual Studio的Designer視圖(如果需要的話,為2008 SP1)中。 但是,在Designer中這很糟糕,尤其是在連接失敗時應用程序嘗試重新連接時。 每次進入Designer模式時,Visual Studio都會凍結約20秒(重新連接超時),這將終止我的工作流程。
您可以檢查控件是否以設計模式顯示:
http://msdn.microsoft.com/zh-CN/library/system.componentmodel.component.designmode.aspx
/編輯:正如人們在對另一個答案的注釋中指出的那樣,DesignMode屬性在構造函數中不可用。 因此,最好的解決方案可能是將數據庫內容移至“ Load”之類的事件中,並在其中使用DesignMode屬性。
通過在我的Program類上有一個名為IsRunning的全局靜態屬性,可以解決此問題。
當程序在main方法中啟動時,將IsRunning屬性設置為true。 然后在用戶控件的構造函數中,我可以輪詢屬性IsRunning以確定我是否執行特定的代碼,在您的情況下,這些代碼將嘗試訪問數據庫...
編輯:這是一些代碼...
private static bool _running = false;
/// <summary>
/// Gets or sets a value indicating whether this <see cref="Program"/> is running.
/// This property is used for design time WSOD issues and is used instead of the
/// DesignMode property of a control as the DesignMode property has been said to be
/// unreliable.
/// </summary>
/// <value><c>true</c> if running; otherwise, <c>false</c>.</value>
public static bool Running
{
get
{
return _running;
}
}
static void Main(string[] args)
{
Initialize();
_running = true;
....
在我的用戶控件中...
public AssignmentList()
{
InitializeComponent();
if (!Program.Running)
{
return;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.