Have you ever thought about switching from Windows Forms (WinForms) to WPF seriously? Try something new and stop to develop along the old well known patterns? To be honest until a few months ago, I haven’t had any thoughts about making a transition. I was very familiar with Windows Forms and WPF would have been something I would have to learn from scratch. So it was only a test project and my applications remained Windows Forms applications. So, when I joined Centigrade earlier this year, after working as a developer for nearly 15 years in the financial industry, Centigrade made the transition to WPF long ago. Just take a look at related blog articles on our website! My colleagues in the field of design engineering are working for several years with WPF. Especially younger designers and design engineers only knew Windows Forms from their study – if at all. They never worked with it in practice. Many companies already use WPF, but despite the fact that already the fourth version of the technology is out lot of them are still in the evaluation phase. From my own experience, I can only report – it can even be worse. Especially, in the financial sector applications with a rather boring look and feel are created until today. Yet, things could be so much more appealing…
So a new chapter started in my programming career. With a healthy dose of skepticism, I joined my first WPF Project. I was hooked immediately. I have collected some of my experiences and summarized them within this article.
Form design in Expression Blend – How to style a WPF application
Who doesn‘t know the good old form designer tool for Windows Forms. Select an item from the toolbox, drag it onto the workspace, adjust its size and text, and your already done. Wow – that went fast, but it looks still rather “standard”. There is not a lot tweaking possible with the standard tools. Button remains button, checkbox remains checkbox. As I started with Visual Basic 5.0 in 1997, all that was very impressing. All programming languages (Cobol, Pascal) I used so far hadn’t a graphical designer but used only a console for in- and output. But today, no one gets impressed by Windows Forms and there haven’t been a lot of visual improvements over the time. Isn’t there anything better?
At first glance on my first contact, I’m a little disappointed; the designer in Visual Studio does exactly the same. I drag a RadioButton from the toolbox and all I see is the standard Windows control. My colleague gives me a hint: Close the project and reopen it in the genuine WPF Designer tool – Expression Blend. A few clicks later and I am right in the template, thus the construction plan, of the RadioButton . My colleague explains the changes that needed to be done to create a RadioButton that looks interesting. Within minutes, we strapped the RadioButton down to its core parts and rebuilt it from scratch with completely different parts. A gradient effect here, a shadow effect there. Quickly, we recreate the States and the original RadioButton is hardly recognizable. As we change the style of the button, I realize how the XAML- editor generates all the code diligently.
A: Standard WPF Style, B: Custom Style, C: Windows 8 Style UI
XAML – design by code made easy
So this is XAML– code. I am a little confused and ask my colleague: „Does this XAML code contain all the changes that we have made in the design view? Can I style the whole button through pure XAML- code as-well? “. In response I get a: “Yes, of course! But even better, you can outsource style and template of the button and assign it to another button instance. For that you can use Resource- Dictionaries.“ My colleague explains how to outsource the control template and style into such a dictionary. His dictionaries already contain various kinds of other styles, colors, brushes and the like and they were all outsourced. Via the key I can now access all of these resources at runtime. Of course, I want to try that out. In XAML I refer to the dictionary and choose a different style for the button. And suddenly it looks totally different.
Designing without programming skills – really?
We continue to work and style layout of our user interface. So far, we have not written a single line of C# code. ”Boring!“ – That tells my first reflex as a developer. Still it’s kind of nice, anyway. As a developer, I can focus on the implementation of the program logic in the future. The interaction with the presentation layer won’t be one of my primary concerns anymore.
„The program logic is partially available already“, says my colleague. “It comes from our clients. We don’t take any influence on that“. Via bindings we only connect the interface with the underlying code. Nice, this is a true separation of presentation layer and logic. So, I let the designer create the interface following my guidelines and then I only have to connect them to my application? That sounds almost too good to be true. And yet it works. My application can be redesigned completelyand yet no single line of C# code needs to be (re-)written. But how does that work?
MVVM – Cooperation between Designers and Developers
The solution is called MVVM (Model-View-ViewModel). This architectural pattern allows a complete separation of presentation layer and presentation logic. Now the view is created almost exclusively through XAML code. It can be created and edited by a design engineer easily – even if the ViewModel (the program logic) is not fully present yet. Only the interface of the ViewModels has to be known.
The ViewModel contains the interaction between the two layers. Other than in Windows Forms I have the possibility to create a so-called “two- way binding“. For example: If I have a TextBox and I want to change its content, I have to do all that via code by myself. Although Windows Forms is capable of data- binding as well, it only works on data sources. A binding to a String variable would not be possible. This kind of binding makes it possible to have the layout released from the code completely. I don’t have to refer to a control by code directly. I only communicate via ChangeEvents through the properties that are specified in the ViewModel. From now on Spaghetti- code with confusing GUI- logic is history and I can assure the correct behavior of the ViewModel through a Unit-Test. But is it always that simple? Is it possible to solve everything in the View-Layer with a designer and XAML code?
Behaviors, Converters, Triggers – initial work for developers?
No, it’s not that easy after all. Between View and ViewModel is yet another kind of intermediate layer with components that are more likely to be attributed to the View- Layer. These components create the “glue” between the View- and the View-Model layers. For example: A simple calculation of two values. There are three text fields in a form. Field one and two contain the values that have to be calculated, field three will display the result. In XAML- code this example calculation is not that simple to accomplish. We need a Converter, which is connected to all three text fields via Binding, and which is capable of calculating the input values at runtime. Especially simple calculations or conversions don’t belong in the programming logic. They get outsourced as Converters. Finally, at this stage we may start programming! This demands the engineer inside the design engineer and less of the designer. Besides the Converters, there are also building blocks such as Behaviors and Triggers … but this would be beyond the scope to explain. I can only say – they facilitate collaboration between developers and designers again many times.
Effects and pixel shaders – take the advantage of hardware acceleration
That’s how it works in the field of visual effects. Imagine you would like to realize a glow effect when you click a button. Of course, this effect should glow above all other controls that are nearby. For this purpose, it would be nice, if the effect is not a semi-transparent rectangle with a gradient inside, but a really nice, vibrantglow in shape of our control as a silhouette (like it is done in Photoshop using so-called “Blendmodes”).
A derivate of the WPF-effect class is needed here – and thus again C # code. So we choose the control, place the effect on it, choose a blend mode and an object which contains the color of our effect. Now a pixel shader has to be connected within the effect itself. What is the advantage of that? In WPF “generic” effects (e.g. the Dropshadow effect) have a lot of features and settings and so they draw a lot of performance. Especially on PC’s which control industrial machines (which is a common example in our field of clients), a simple and fast solution is necessary. To realize the Blendmode that we talked about earlier, we integrate a custom pixel shader. This only includes the major effect without a lot of user settings. Pixel shaders are programmed in HLSL (e.g. with the magnificent Shazzam editor) and they don’t take a lot of performance, because they are rendered by the GPU of the graphics card. Now, the CPU doesn’t have to calculate them anymore. I can place the effect on top of the main content layer in WPF – the AdornerLayer. So the background takes influence of the glowing color. This kind of layer model is not included in Windows Forms – creating effects isn’t either.
Scalability – optimal rendering quality in every resolution
This takes us to the next topic: the scalability of the interface. Have you ever tried to scale a Windows Forms application? You can bind controls to the screen to change their size and alignment dynamically – but scaling? During my time as an IT-manager, I have seen some strange things. A former colleague had set a resolution of 800×600 pixels to her 24“ LCD display. The standard resolution for this type of display is 1680×1080. When I asked her, why she uses the low resolution, she answered: “Because otherwise everything is so small!” The application, in which she works mainly, is designed for a resolution of 1024×768 pixels. Now, if you work on such a large display and you scale the application’s window up, you haven’t made things easier. All controls remain in the same size. So does the nice high-resolution LCD display become obsolete? No! In WPF I can design my layout in such a way that I can scale its size individually – without a loss of quality, because it is all vector based. So, a WPF application renders razor-sharp on all kind of screens and DPI. Especially with the interfaces of industrial machines, which resolutions can vary heavily, it is a must-have.
Touch operations – better realize it in WPF
Speaking of machines terminals – these don’t have input devices like mouse and keyboard usually. Generally they are operated through touch operations. Especially with complex functionality, gestures with one or more fingers are inevitable. Anyone who owns a modern smartphone or a tablet-computer knows these gestures. Even the upcoming Windows 8 is designed for gestures. So, did you ever try to dive into the topic of touch gestures in Windows Forms? No? Well you better don’t even try. The implementation for touch devices is as good as none existing in Windows Forms. A one-finger click on an object is the highest of highs. Everything beyond that is almost not realizable in the rational use of resources – if it is possible at all. As we all know, there is almost nothing impossible within this topic, but why don’t we use the provided tools of WPF from the start? This is much easier and even complex gestures can be implemented without too much effort.
Attaching Data – WPF and the entity framework
Last but not least, one of my favorite topics – the integration of databases. I spent a long time working with data accesses using DAO, ADO and ADO.Net and I have known the Entity Framework only for a short amount of time. Especially with topics that you feel confident with, you become very critical to new things. But even here, I can’t find something to nag about. The connection to WPF works via data-binding, like in Windows Forms. Elements that contain multiple records (e.g. ComboBox and Grid) are connected to an ObservableCollection as data source. This collection tells the UI to refresh automatically so it represents always the current data status.
The actual access to the data only works in the program logic, and thus not in the field of design. The big advantage is that the design engineer, while constructing the views, doesn’t have to deal with the issue of data provenance. Even at design time, not at run-time, the designer in Expression Blend can work with sample data and start styling right away until the sample data is eventually replaced by the real database data. This is also the case in Windows Forms, but there you can’t use DataBindings if you don’t have a direct communication to the data source. Despite my critical point of view, I couldn’t find any disadvantages of WPF for Windows Forms.
Conclusion – what remained of Windows Forms
Admittedly, it’s not quite easy to work with WPF. You have to learn it and get quite some practice. In particular, the transition from the solid connection between interface and program logic in Windows Forms, to the MVVM pattern in WPF, provides challenges at the beginning.
Once you passed these difficulties and you internalized the logic, the benefits of WPF speak for itself quickly. Today, Windows Forms doesn’t have any serious advantages to WPF. All the good approaches of Windows Forms have been implemented and improved in WPF. In addition, new features for effects and graphics have been implemented. If you know how to deal with WPF, also the frequently-read-about performance issue is not as dramatic. For me as a developer, a completely new world of design and usability was shown. Now, beside its great functionality (hopefully), the application can score with a great interface and usability. And just between us, in the age of smartphones and tablet-computers, who longs for his old VT-100 terminal…
If you are interested in learning more about how we approach projects feel free to have a look at our Engineering service page.
One year later: helpful WPF tools (not only for former WinForms developers)
After nearly a year full of new experiences in WPF I would like to update this blog article – and introduce to you a couple of useful tools, which, over the course of the past year, made working with WPF a great deal simpler for me:
- WPF Inspector: investigates a running WPF application and lends a hand on troubleshooting layout and styling
- XamlBoard: supports your working process by creating WPF themes, facilitates screen styling and optimizes Xaml ResourceDictionaries regarding their performance
- Snoop: displays the Visual Tree of a running WPF application
- Xaml Styler: styles Xaml code in a well-defined format that leads to a clean commit in a project with several developers
- Shazzam: editor with a preview function that easily creates PixelShaders. The compiled PixelShader and generated effect class can be included into the project immediately
- Dependency Property Generator: its name says it all 😉
Download and try it out! Each of those tools provides a supplementary addition to the functionality of Visual Studio und Blend.
All trademarks or registered trademarks are properties of their respective owners.