Jerry Nixon @Work: Stacking User Controls in WinForm applications

Jerry Nixon on Windows

Friday, March 5, 2010

Stacking User Controls in WinForm applications

If this is not your current pattern, then reconsider your current pattern. This pattern is very reliable and well proven.

The idea is simple, your windows application has more than one screen to display to your user. You encapsulate functionality in user controls (typically better than a form – not always). You surface user controls to the user when they click a button or interact with the UI. Yes, it’s that simple.

How to you manage those controls in your application?

The Microsoft Patterns & Practices Composite UI Application Block addresses this in their Smart Client guidance (see here). But this is very out of date. And their block, though effective, is a lot of overhead for something you can manage in around 30 lines of code.

This has nothing to do with the event model or command pattern. Both of those are fully supported because all we are doing here is handling our user controls. All we are doing is responding to the user’s request for content. And there’s plenty of room to customize this to your own uses.

Here’s the run through.

  1. A user clicks a button (button_click()) or somehow starts
  2. Button_Click() calls LoadControl()
  3. LoadControl() searches for your user control using GetControl()
  4. GetControl() looks in panelContainer’s control collection
  5. If the control is not found, LoadControl() creates & adds it
  6. If the control is found, LoadControl() references it
  7. The User Control is brought to the front of the container
  8. [/end]

If you want to add your controls through design time, this approach does not care. You can do that. But if you don’t then this supports that, too.

I have seen these controls implemented with a custom interface (to recognize them) and a Activate() method to alert them they were selected.

The sky is the limit insofar as variations. But the core functionality is exactly as I have illustrated below. Look at how simple it really is:


Get the code here: