天天看点

winform 自定义布局器

自定义一个控件的布局器,示例控件为容器panel。

重点在于要清楚自定义控件与布局器的调用关系,至于布局器内部的实现过程根据自己想法而定。

//面板
    class UserPanel:Panel
    {
        UserLayoutEditor editor = new UserLayoutEditor();
        public override LayoutEngine LayoutEngine
        {
            get { return editor; }
        }
    }
    //布局器
    class UserLayoutEditor : LayoutEngine
    {
        public override bool Layout(object container, LayoutEventArgs layoutEventArgs)
        {
            UserPanel usercontainer = (UserPanel)container;
            int width = usercontainer.Width;
            int height = usercontainer.Height;
            int left = usercontainer.Padding.Left;
            int right = usercontainer.Padding.Right;
            int top = usercontainer.Padding.Top;
            int button = usercontainer.Padding.Bottom;
            width -= (left + right);
            height -= (top + button);
            int gap = 2;
            foreach (Control control in usercontainer.Controls)
            {
                control.Location = new Point(left, top);
                control.Size = new Size(width, control.PreferredSize.Height);
                top += control.Size.Height;
                top += gap;
            }
            return base.Layout(container, layoutEventArgs);
        }
    }
           

继续阅读