Tip:解決DesignMode不能正確反應是否處於設計模式的問題

來源:互聯網
上載者:User
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.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.