28 December 2007

Jockin' Screens

by mo

So another thought that came to mind was the concept of how to switch views in a winforms application. Bare with me because these are only thought so far and I have yet to read about the actual “Application Controller” pattern in PoEAA.
I’ve been reading a book on WinForms lately by Chris Sells, the name evades me at the moment but I promise to give you the name in the future. And it tells about the ApplicationContext and how it works and how you can access it.
If you take a look at the overloads for the “Application.Run()” method you’ll find one that accepts an ApplicationContext. When you choose the overload that accepts a Form it creates an application context and registers for the form closing event which is when it call Application.Exit().
If you can access the context then you can access the start up form, and if you need to switch user controls on the main form you can try to access the application context to do so. Here’s my 30 second brain dump on potentially how this could work… (Warning… I have yet to fully implement this!)

    public class ApplicationController
        private static System.Windows.Forms.ApplicationContext _context;
        private readonly IScreenRegistry registry;

        public ApplicationController( IScreenRegistry registry )
            this.registry = registry;

        public static void Begin( )
            Application.EnableVisualStyles( );
            Application.SetCompatibleTextRenderingDefault( false );
            _context = new System.Windows.Forms.ApplicationContext( new Form1( ) );
            Application.Run( _context );

        public void Render( IScreen screen )
            _context.MainForm.Controls.Add( registry.FindFor( screen ) );

Main then becomes an empty shell that delegates to the application controller, when types in the system need to render a new view it can call upon the ApplicationController to take care of that by calling it’s Render method and passing in the screen to display. The application controller can then leverage registry to find the user control that’s registered for the screen.

Hey, if anyone knows a good book on WinForms patterns of even UI patterns I’d love to hear about it!


csharp designpatterns