Friday, November 16, 2012

Making sense of WPF layouts

I started out as a Swing developer and I have the Java Foundation Classes book to prove it. But Swing never really caught on and so I started working with C# and WPF. Windows Presentation Foundation (WPF) isn't what you'd expect for making desktop applications. It kinda feels like making web applications since you "describe" the UI via a XML-like language called XAML. This isn't really a bad thing just different.

I could go on about WPF being different but at the end of the day the foundation of a desktop app is the layout it's built upon. This is what I've learned.

  1. By default, WPF apps have a base "Grid Panel" layout. Get rid of it and use "Dock Panel" as your base.
    Dock Panels are the same to Border layout in Swing. The idea is to place the menu on top (DockPanel.Dock="Top"), status bar bottom (DockPanel.Dock="Bottom") and put a "Grid Panel" at the center. Now you have a well-behaved desktop app that reacts well to window re-sizes. 
  2. The Grid Panel is like Swing's GridBagLayout only easier to use.
  3. Use the Alignment properties in combination with Margin to position elements in a panel; avoid fixed positions (using the x,y coordinates) unless you have a really, really good reason to do so. They don't work out so well when tested against various screen resolutions.
  4. Also, the same for height and width. Use min and max properties instead.
  5. Don't use blank "label" components to separate components. Use the margin and padding properties. For example, if 2 buttons are side by side, don't put a blank label in-between them to create space.