Thursday, June 17, 2010

Working with LayoutEngine

When you developing your custom controls sometime it requires a certain behavior or graphical representation of it child controls .
In this case you Control have a property called LayoutEngine
Example below shows you how to implement your LayoutEngine 

     public class DemoPanel : Panel
    {
        private bool m_CustomLayout = false;
        private DemoPanelLayout layoutEngine = new DemoPanelLayout();

        public DemoPanel() { }
        public bool CustomLayout
        {
            get { return m_CustomLayout; }
            set { m_CustomLayout = value; }
        }
        public override LayoutEngine LayoutEngine
        {
            get
            {
                return layoutEngine;
            }
        }
      }
Now for the custom LayoutEngine implementation


    public class DemoPanelLayout : LayoutEngine
    {
        public override bool Layout(
            object container,
            LayoutEventArgs layoutEventArgs)
        {

            Control parent = container as Control;
            if (((parent as DemoPanel).CustomLayout))
            {           
             Rectangle parentDisplayRectangle = parent.DisplayRectangle;
             Point nextControlLocation = parentDisplayRectangle.Location;
           
            foreach (Control c in parent.Controls)
            {               
                if (!c.Visible)
                {
                    continue;
                }
                if (nextControlLocation == parentDisplayRectangle.Location)
                {
                    nextControlLocation.Y += c.Margin.Top;
                    nextControlLocation.X += c.Margin.Left;
                }
              
                c.Location = nextControlLocation;
                if (!((c.Location.X + c.Width + c.Margin.Left)> (parent.Width - c.Width-c.Margin.Left)))
                {
                    nextControlLocation.Offset(c.Width+c.Margin.Left, 0 );
                }
                else
                {
                    nextControlLocation.X = parent.Left+c.Margin.Left;
                    nextControlLocation.Offset(0,c.Height+c.Margin.Top);
                }               
             }
            }
                       
            return false;
        }
    }


In example above DemoPanel's LayoutEngine will check the CustomLayout property
and order child controls as tabled view .

1 comment:

  1. Thanks for this example :)
    I know it was posted some time ago, but it is still actual.

    ReplyDelete