C# Refactoring – Switch Complex WinForms App to WPF MVVM

cmvvmrefactoringwpf

This question is connected with my older question C# Application GUI design dependent on configuration.

I have built quite big WinForms application working in industry for a few years. It communicates with many HW devices. Application can be configured to use or not use some of these devices and GUI is modified by this configuration. Now, even more devices (and application possible configurations) are going to be added, so I need to refactor whole application, maybe even write the most of it again and it will be very painful work as it was generally my the first bigger project.

Finally, I decided to start learning WPF and I'm going to rewrite this application again using WPF, partly because I feel that such complex WinForms application isn't easily extensible and maintainable, partly because I want to learn WPF anyway in the future.

I want to use it properly and separate business logic from UI. I came across some MVVM tutorials using WPF, but all of them are very simple. My application has quite complex menus, few DataGridViews, and PixtureBox, which I'm drawing some measured 2-D stuff onto.
As I said, application communicates a lot with several devices as well as with SQL server both-sided, and of course it has many threads. Also, there is quite a lot of miscellaneous dialogs.
At this moment in WinForms version, it's mess of logic and UI mixed together.

Can you suggest me any approach, how to start separating logic from UI in such kind of complex project?

I've read many WPF/MVVM tutorials, but all examples are simple, of course, and I'm not able to think in MVVM enough yet.

Best Answer

It's the same approach as with any other major refactoring.

  1. Built unit tests to validate the behavior of the existing code.

  2. Identify and isolate small sections of code that can be refactored.

  3. Refactor one section at a time.

  4. Verify that all unit tests (see step 1) continue to pass. If they fail, fix your refactoring.

  5. Rinse and repeat until you regret the day you ever decided to refactor the code base.

  6. Eventually you'll complete the refactoring. Swear off code-behind and promise yourself that you'll never, ever make those mistakes again.


As far as how to separate out business logic from UI logic within MVVM. For the most part, all of your business logic should live at your Model layer or lower. All UI related logic, including properties to be bound to, will live at the View and ViewModel layer.

A good rule of thumb on "Is it business logic or UI logic" is the following. If the behavior of the code should persist regardless of what the UI is, that's business logic. If the code's behavior is tied to the presentation of the data, that's UI logic.

Related Topic