Reviewing WPF and MVVM

 I've been working in WPF (Windows Presentation Foundation) a lot lately. WPF is a great way to build a Windows desktop application, it's been around for many years and is very mature compared to UWP (Universal Windows Platform) which is a similar tool for creating desktop applications. It's not the newest, shiniest tool but it is definitely a great tool to be aware of. A while back I built a simple WPF program that worked with a .NET function library that did very simple distance calculations, and I decided to review that before really getting into more advanced concepts.

When the program runs, it looks like this:

 

It's nothing too fancy, but it will show travel time, rate of travel and distance traveled over time. It also allows an excel spreadsheet to be inputted and it will run many calculations and then update the spreadsheet. The layout here is primarily built using the XAML grid, a staple of any WPF application. The grid specifies how many rows and columns the grid will have, and when I create a field or text block, I tell it what grid it belongs to. The field for the spreadsheet file path covers columns 2 through 4, and is in the first row. The XAML code that is used to build this window is the second V in the MVVM pattern, the View. The view is what you see, but the input fields and buttons all have code that run in something called the View Model.

In the View Model, we use commands that can alter the properties found in our Model (Model View View Model, the acronym is complete). The Calculate button for example, is going to change the values of our travel time, rate of travel and distance traveled, which are all properties of the Calculator model. When the CalculateCommand is called, the calculation is added to the history (that History tab tracks all of the calculations we made), and then the calculations are made and we use RaisePropertyChanged to actually show the new values in the View.


 

 MVVM is a great pattern for WPF applications. In this simple project, I could have probably gotten by without a formal pattern, but MVVM can be very helpful on larger projects especially. The View Model presents data from the Model in a way that the View can properly work with it, and it also protects the Model from being changed directly in the View. These patterns are meant to reduce complexity, and I've found that by learning the MVVM pattern it makes it much easier to read code that is following an MVVM pattern. You can find the code for this WPF project, as well as a similar project in Windows Forms, here on my GitHub

Comments

Popular posts from this blog

API's in C#

Using WebRTC to build a videophone in React and TypeScript