• Tip:解决DesignMode不能正确反应是否处于设计模式的问题


    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.
  • 相关阅读:
    Error (0xc0000225) installing Windows 8 R2 on VirtualBox
    网页宽高自适应大小
    C# Java DES加密解密
    JS获取DropDownList的value值与text值
    用Aspose.Cells控件读取Excel
    Extending your SharePoint 2007 site with Microsoft ASP.NET AJAX 3.5
    页面自定义拖拽布局
    OutLook 2010 收件箱子文件夹收到新邮件时没有桌面通知
    PeopleEditor的取值及赋值
    deprecate (声明不赞成)
  • 原文地址:https://www.cnblogs.com/deerchao/p/950675.html
Copyright © 2020-2023  润新知