VS內建的可視化表單編輯器很好用,但是也有一些煩人的問題,比如:
- 無法編輯繼承自虛基類或範型基類的Control/Form;
- 有時DesignMode這個屬性不能正確反應是否處於設計模式--詳細地說,就是嵌套在自訂控制項B裡的自訂控制項A, 如果B被放到另一個控制項/表單上後,A的DesignMode屬性就不能正確反映它所處的環境了;
等等...
對於前者,確實有一些辦法可以將就,但是通常來說,你在用了這些方法之後,只會更恨Visual Studio(如果你真的想知道的話,好吧,先寫一個繼承自原來的基類的非範型非虛擬基類,然後子類以此類為基類就可以進設計模式了);而後者,確實是有辦法讓你忘記這些不快.
代碼:
class VSDesignerFix
{
// Returns True, if specified control or one of their parent control is in design mode.
public static bool IsInDesignMode(Control control)
{
if (control == null)
{
throw new ArgumentNullException("control");
}
bool result = false; // return value
Control ctl = control; // checked control for design mode
do
{
ISite site = ctl.Site; // get the site object, which is set by designer
if (site != null)
{
result = site.DesignMode; // check for design mode
if (result) { break; } // if control is in design mode then loop ends
}
} while ((ctl = ctl.Parent) != null); // track the parent control
return result;
}
}
使用方法:
public class MyControl : Control
{
public MyControl()
{
}
protected override void OnLoad( EventArgs e )
{
base.OnLoad( e );
if ( !VSDesignerFix.IsInDesignMode( this ) )
{
//在這裡輸入不需要在設計模式下啟動並執行代碼
}
}
}
上帝的歸上帝,凱撒的歸凱撒,這個Tip歸功於Jakub Mller.