Posted by: Zeeshan Amjad | July 18, 2009

Writing Custom Layout with C#


 

Layout defines the size and position of the control on the screen in WPF application, to be more specific in the window or page. WPF already define few layouts such as Canvas, DockPanel, Grid, StackPanel, WrapPanel etc.

If we want to make our own layout then we have to inherit our class from Panel and override at least two of its member function name MeasureOverride and ArrangeOverride. WPF uses two step process to decide the position and size of the element in window or page. First it calls the MeasureOverride method to calculate the size of all of the child elements in the layout. The second step ArrangeOverride actually calculates the position of the element in the layout class.

Here is one of the simplest possible implementation of my own layout. This layout is don’t nothing very fancy and display everything at top left corner of the screen.

  1: public class MyLayout : Panel
  2: {
  3:     protected override Size MeasureOverride(Size availableSize)
  4:     {
  5:         Size childSize = availableSize;
  6: 
  7:         foreach (UIElement child in InternalChildren)
  8:         {
  9:             if (child != null)
 10:             {
 11:                 child.Measure(childSize);
 12:             }
 13:         }
 14: 
 15:         return new Size();
 16:     }
 17: 
 18:     protected override Size ArrangeOverride(Size finalSize)
 19:     {
 20:         foreach (UIElement child in InternalChildren)
 21:         {
 22:             child.Arrange(new Rect(new Point(0, 0), child.DesiredSize));
 23:         }
 24: 
 25:         return base.ArrangeOverride(finalSize);
 26:     }
 27: }
 28: 

And here is the usage of this layout.

 

  1: public class MyWindow : Window
  2: {
  3:     private MyLayout myLayout;
  4:     public MyWindow()
  5:     {
  6:         Title = "Hello World";
  7: 
  8:         myLayout = new MyLayout();
  9: 
 10:         Button btnTest = new Button();
 11:         btnTest.Content = "Press Me";
 12:         btnTest.Width = 100;
 13:         btnTest.Height = 25;
 14: 
 15:         myLayout.Children.Add(btnTest);
 16: 
 17:         Content = myLayout;
 18:     }
 19: }
 20: 
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: