Separating the view in Visual Studio GUI Applications using Design Patterns

I am working on a little file copying program for my company and it's getting large enough that I'm starting to care about code design (I know, I should have from the beginning...).

Right now my problem is that I want my form class code to be as lean as possible. Based on my research, it sounds like I want to implement Duplicate Observed Data in order to keep the View decoupled from the rest of the program. Are there any tips on how to do this in VS2010/C#? Or are there better ways to do what I want to do?

I'm using Visual Studio 2010, .Net 4.0, C#, and it's a Windows Forms Application.

Suggestions on tutorials, books, or open source examples are welcome.

Edit: I just found this article about the MVP pattern, which is probably relevant to me. But I'd still appreciate input.

-------------Problems Reply------------

We've approached this in past projects by applying a modified version of the MVVM pattern (usually associated with WPF) in Windows Forms. There is a lot of boilerplate code, so get your typing fingers ready, but it pays off very well in the long run.

Obviously, this is very long and will probably be overwhelming. Take your time and implement each piece at a time. It is worth noting that in WPF, many of the work below is done for you.

First, we start with three name spaces: (for extra points, put each namespace in a separate assembly, but that is not required.

  • CompanyName.ProjectName.Models - Contains your domain objects (including collection classes).
  • CompanyName.ProjectName.ViewModels - Contains various view model classes (see below)
  • CompanyName.ProjectName.Views - Contains your Forms and UserControls

Creating Domain Classes

  • Start as simple as possible, mostly just properties with getters and setters.
  • For each public property of interest in each class, create matching Changed events. For example, create an event called NameChanged if you have a property called Name. The event should be raised from within the setter every time that property's value changes.
  • Create public methods containing business logic, such as Delete(). These methods should throw exceptions if there is an error. (In more advanced designs, you may wish to have a controller object that contains the business logic.)

Creating ViewModel Classes

A ViewModel class is mostly a designer code-behind class "on steroids", except it doesn't have any knowledge of the actual controls or layout of how it will be used, just behavior. Usually there is one ViewModel for each Model class, but you can also make a ViewModel such as ClassroomView that displays a List<Student>.

  • Create an public, abstract ViewModelBase class that implements IDisposable and INotifyPropertyChanged.
  • Create classes for each domain object you want to visualize, or group of objects you want to visualize. These classes should inherit from ViewModel.
  • Create read-only public properties for display in the view model class that represent what you want to display on the screen. For example, in the PersonViewModel class, if you want to display a full name, create a property called FullName, where the getter could concatenate the FirstName and LastName property of an associated Person model.
  • Each ViewModel class should also have a property that relates to the underlying data model object.
  • Create other read/write public properties for display, such as:

    • bool properties like IsHeadOfHouseHousehold for binding to checkboxes or radio buttons.
    • Color properties like HighlightColor for binding to BackColor/ForeColor/etc of various controls.
    • string properties that allow the underlying data model object to be edited, by binding to textboxes.
  • When the ViewModel object is constructed, it should register for all of the events for the underlying data model object, such as FirstNameChanged. In the eventhandlers, you should raise the PropertyChanged event for any properties in the view model that are affected. For example, the handler for the FirstNameChanged event should raise PropertyChanged for FullName.
  • In the Dispose method, you should unregister from the data model events to prevent memory leaks.
  • Create public methods that represent user actions and commands they can perform, such as Delete(). The methods should be written from a user perspective, so that they can raise dialog boxes to say "Are you sure?" Then they should call methods on the data model object, or some other controller object.

Creating Views

OK, now the easy part:

  • Add your ViewModel objects as project data sources in your solution.
  • Create forms and user controls by laying out the controls you want on-screen. Create TextBoxes, DataGrids, etc. For each property that should be bound to a ViewModel instance, use the (DataBindings) property to bind to your project data sources. As you create databindings, it will automatically create BindingSource components.
  • In your main form, create an initial instance of your data model, load from disk, etc.
  • Where necessary, create instances of the ViewModel classes and set the DataSource property of the appropriate BindingSource. The interface will automatically come to life.
  • For buttons, write the Click event handlers to call the appropriate public method on the ViewModel.

The End Result

  • You have easy to modify data model objects. Changes to the data model won't affect the user interface.
  • You have easy to modify view model objects. If you want to change the program's behavior, the data model doesn't have to change, nor does the control layout. If more than one form or user control uses the same view model, you have consistency between different views in your program.
  • You have easy to modify forms and user controls. If you want to the change the look and feel, you don't have to worry about modifying the program's behavior or data model. The code-behind for each form is tiny.
Category:c# Views:0 Time:2012-01-20

Related post

  • Where is the Xap file content viewer in Visual Studio? 2010-09-21

    Where can I find following viewer within Visual Studio? --------------Solutions------------- That's Silverlight Spy, which you can get from here: It's a commercial product, but it has a trial period. If y

  • Custom Server Control that can be dragged into design view in Visual Studio 2009-03-23

    How do I setup a custom server control, so that it can be dragged into a design view in Visual Studio? I have create a separate ASP.NET Server Control project and a custom MailLink control, basically by copying the code from this MSDN article: How to

  • Class view in Visual studio 2009-08-25

    I see that I would benefit from using the class view in visual studio. It would give me better overview over my classes, their methods and make it easier for me to see where and when to refactor my class. I assume that it would give me a better struc

  • how can i disable close button of console window in a visual studio console application? 2011-05-19

    I need to disable the close button in the console window of a visual studio console application written in C#. I want that the application should run until it completes and the user should not be able to stop it by closing the console window. I am us

  • What to use instead of Visual Studio for Applications? 2011-07-30

    What is the Microsoft successor to the obsoleted Visual Studio for Applications (VSA) technology, or what is a good alternative? Obsoleted API --------------Solutions------------- From what I've seen, the answer is PowerShell - a full .NET powered sc

  • Hide master pages when using design view in Visual Studio 2011-11-17

    Is there a way to hide master pages when designing a child ASPX page using the Design view in Visual Studio 2010? My master pages handle some navigation controls and a login that totally freaks out when rendered in the Design view. --------------Solu

  • Compile a C# visual studio console application in mono (mac) 2013-02-09

    I am pretty new to mono and C# so this is probably a simple question, but i cannot find the answer. I need to compile a C# visual studio console application on my mac. I thought mono would be right for that purpose. I don't know which file to compile

  • Visual studio 2005 application stopped working after windows 7 32 bit OS update to service pack 1 2013-09-18

    Hi Support, I have Tutor product which is used to record the Windows Application for learning process. It is a 32bit application which works fine in Windows XP OS and Windows 7 32 bit OS. But after the upgrade of Windows 7 to Service Pack 1, it is no

  • Why is keyhelp.ocx failing in my Visual Studio C++ application? 2013-12-06

    Using keyhelp.ocx to display popup HtmlHelp in a modern Visual Studio C++ application fails. I get a COM exception with no sensible error code. Looking at the debug output, there seems to be an Access Violation behind the scenes. --------------Soluti

  • How do you force Visual Studio to regenerate the .designer files for aspx/ascx files? 2008-09-05

    Sometimes when I'm editing page or control the .designer files stop being updated with the new controls I'm putting on the page. I'm not sure what's causing this to happen, but I'm wondering if there's any way of forcing Visual Studio to regenerate t

  • What are the various components of Visual Studio Team System each designed for? 2009-07-05

    What are the various components of Visual Studio Team System each designed for? Our company was recently accepted to Microsoft BizSpark and now I have a blizzard of options to choose from. Right now I'm just needing version control and a coding envir

  • Visual Studio 2005 Windows Forms Designer - "Object reference not set to an instance of an object" 2010-06-14

    I have a Windows Forms form that I am adding some new functionality to. The form has roughly 100 controls on it. I discovered when looking at the "properties" dropdown that there were several dozen controls in the form that served no purpose and were

  • Visual Studio, Linq-to-Sql, designer settings? 2011-01-23

    Is there some place I can change output settings for the Visual Studio Linq-to-Sql designer? I would like to control if table names are pluralized/depluralized, add specific attributes, namespace etc. Can something of this be done without manually ch

  • C++ - Qt - Visual Studio 2010 - application with both gui and console 2012-04-18

    If no arguments are given to the program it launches as a GUI application, if it is given args it is run through the command line. I was able to get visual studio to display and print to the console with Properties>Linker>SubSystem (Console/SUB

  • Should the Visual Studio GUI editor be used? 2008-10-09

    Coming from a background, I'm familiar with GUI editors that do a poor job of producing code. However, I've never written a GUI using .NET. Does the GUI editor in Visual Studio have the same problem(s)? Are both the source files and output GUI good?

  • How to set default XAML view in Visual Studio 2008 2009-08-26

    In Visual Studio 2008, when you add a new XAML window to a WPF Application Project, the default view you get is "split view" where the visual designer and the XAML code are shown one above the other in the same document. I prefer an alternative view

  • Running Visual Studio console application in debug mode consumes no more than 50 percent cpu usage 2009-10-13

    I have a several C# console applications that basically parse tons of data in memory (LINQ) and output the results to a text file. Now, forget about the writing to the text file for a minute because this is not where the problem is occurring. When I

  • Visual Studio 2008 - Application running slower once built 2010-08-16

    I have a chess game I have created in Visual Studio 2008. It runs very well when I am debugging, but now I have finished and built the program, it lags a bit and I'm finding it a bit annoying as it was running so well in when creating/debugging mode.

  • Help Viewer in Visual Studio 2010 2010-08-25

    When I installed Visual Studio 2010, i figured out that it was not having a traditional windows based Help Viewer. The help topics were loaded in the Internet explorer. I understand that online and offline help will be consistant if we use IE. Other

Copyright (C), All Rights Reserved.

processed in 0.093 (s). 11 q(s)