I am currently working on a large app that is using WPF as its UI technology. I’m on a small team of talented developers (i.e. I think my colleagues are talented!) and we came at WPF six months ago from scratch, although everyone apart from me had WinForms experience.
As we built our app, we made frequent use of the WPF UserControl. I think the main reasons for this were:
- Visual Studio lists UserControl as an item and this encourages its use.
- It’s a convenient container for XAML that can be reused anywhere.
- It feels WinForms-ish and allows you to do whatever you like in the code behind
As we got further into the project, however, it soon became apparent that UserControl allows you to do things that don’t fit very well with “the way of WPF” and we have pretty much refactored out every UserControl in the app, in favour of DataTemplate, ContentPresenter and custom controls, e.g. sub-classes of ContentControl.
This is very much inspired by the Prism project and the use of Model – View – ViewModel (see Dan Crevier’s blog for a good description of this), which we have found a very natural way of structuring the app.
From my experience so far, I’d observe the following:
- DataTemplate rocks as a way of representing data in the UI
- If you need to wire things up, bindings and triggers are the first things to think about
- Code behind comes relatively low down on the list. Certainly, if a lot of behaviour is going in the code behind I would think quite hard about why.
I’m still in the early days of my journey with WPF, but I’m very impressed with DataTemplate and the use of M-V-VM. I wanted to get my experiences with UserControl out there and see if anyone else has had similar experiences. What are the legitimate uses of UserControl? Any comments?