Model-View-ViewModel in WPF - wpf

I've currently noticed that many people start using this model very often. Anyways, I think it's very correct to separate logic from presentation.
What more, some functionalities cannot be accomplished without it, or just very hardly.
Consider a Tree that is selectable, has search capabilities etc..
But in some cases, you don't need to implement this MVVM model, although people do it.
Do you think it's correct? Wasn't the purpose of WPF to simplify coding - try to do the majority of work in XAML?
I have a feeling, that this model is often misused just for the elegance of the design, but breaks the WPF efforts.
Or am I completely wrong?

imho WPF is designed to use MVVM, so if you writing your code without this pattern will lead you sooner or later into a situation where you have to do some hacks to solve problems.
For me there are very few reason not to use MVVM, like private projects, tryout's, ...
In larger projects, everything should be written in MVVM because of the capabilities of this design pattern (enabling unit tests, prevent miss-use of UI, ...)

The main purpose of seperating logic from UI is for the testability. Since you are putting all logic under ViewModel, you can write the test script for testing your logic without UI.

The issue is that there is a lack of tools so it hard to pitch wvvm when someone has to write half a page of code to throw a messagebox when a button is clicked.

Related

How can I write WPF efficiently?

When I first learned about Microsoft's then-new framework for developing desktop applications, WPF, I thought that one of the biggest benefits of it would be its efficiency. After all, I already know what the GUI controls and elements were that I wanted to use--I just have to slap them all on the page and then wire up all my bindings right, and I'll be done. After that, I learned about the MVVM pattern, which promised clean separation of concern within my WPF app.
I thought this was going to be great! I got into creating several different admin and data entry WPF apps with my team at work, and thus I began to crank out working software with robust but simple GUIs, right?
Not so fast, there, cowboy coder. My experience is that writing WPF is S-L-O-W.
Well, at least the way I do it. You see, after I have a picture of my GUI on a whiteboard, I code up the XAML with the controls that I want. This part, as expected, is fast--laying out the whole of a window is pretty quick. After that, its all the little stuff you want these elements to do takes awhile. I always seem to want to make this text bold in some cases; show a red error box in these other cases.
Then things unravel: this binding isn't working right over here--I have to write a converter and adjust the layout for the right values. Whoops, I forgot that extra NotifyPropertyChanged there. Oh, and I want to use a different template in this state vs. that, so I have to figure out what I can use to swap the templates in certain situation. This data is coming in asynchronously, so I need to make sure the right thing is happening on the right thread and that Property gets NotifyChanged as well. Crap, when I maximize my window, it doesn't stretch like I thought it would--must be because its container height isn't defined, but I don't want to define that, so I have to make it stretch in its parent. Oh, now I really want to make a user control out of this stuff over here, so I better implement some dependency properties...
On and on I go, spending hours and days on stuff that just feels so small and minor. I soon resort to cutting usability features and look-and-feel enhancements because this is taking just too darn long.
Does anyone have any tips or principles I need to try in order to write WPF efficiently?
A couple of things that have saved a lot of time for me:
Use DockPanel as your default panel for layout unless you have a good reason not to.
Keep a folder full of useful classes: a ViewModelBase class that implements INotifyPropertyChanged, a RelayCommand class, etc. There's no need to get fancy and try to make this a separate assembly that you build into your project; just write reasonably good implementations and copy/paste them into your new projects.
Get Resharper and use it. Use templates for creating dependency properties, properties that do change notification, and commands.
Find or build a good library for asynchronous task management.
I find that even for very simple applications I get more done faster with WPF than I did with Windows Forms. For applications that aren't very simple, there's absolutely no comparison.
For the most part, WPF applications are a lot of work to develop because it's harder to make the case for cutting out UI features. You can't just say, "Oh, that's not possible," because it probably is possible (whatever "it" is).
Write your own library, or find an existing one.
WPF is great, but out of the box it is missing some things that would make coding faster. I got tired of writing the same things repeatedly, so I ended up creating my own library full of things like converters, visual tree helpers, attached properties, custom controls, etc., and since then, my development time has sped up considerably.
In addition to my own library, I've also started using Microsoft's Prism and Galasoft's MVVM Light Toolkit. Both contain useful objects that I use all the time and are better than what I could code on my own. (Most used are NotificationObject from Prism, RelayCommand from MVVM Light Toolkit, and EventAggregator or Messenger from either one depending on the project, etc.)
Another thing I've done to speed up coding time is to take advantage of Visual Studio's macros. For example, to create a property with Change notification, I write the private property, hit Ctrl+E, Ctrl+R which generates the public version, then run a macro which automatically sets up the PropertyChanged notification in the setter method.
I almost never change the setter methods from the default macro'd one, and instead use the PropertyChanged event to handle any changes that should occur on the setter. This not only makes it easier to track application flow, but also greatly reduces the time I used to waste browsing through my public properties to alter a setter method.
I believe the right answer isn't for WPF at all, but it can fit what you're looking for.
Most of the times, when you want to leverage a new technology there's a time while you're not efficient, productive and your solutions aren't that impressive, innovative or just doesn't look like others.
What will give you more efficiency is working with WPF itself.
It's more about project management topics than programming. After finishing some project, your team and you should go to some room and discuss:
Success stories.
Problems during development.
Pros and cons.
Fails in the application architecture.
Communication problems within the team and customer.
... and so on.
If everyone shares their knowledge, project manager or team leader does a good job documenting each project story, finally everyone will have a "know-how".
In addition, it's important that you won't need to reinvent the wheel for every new project: if some pattern worked fine, do the same way next time, even if it's not the best way of doing it. And try to enhance it, if possible.
Design patterns, technologies, paradigms, languages, companies, colleagues and nothing are a silver bullet: Microsoft said WPF is a step-forward in Windows client developments, and it is that: a more modern approach to provide shinny user interfaces and a programming paradigm that fits nowadays' desired approaches, easing the relation between coders and designers, as WPF has XAML, which allows not only separation of concerns, but separation of professionals by area (designers, UI programmers, business programmers, ...).
Finally, as I said above, WPF won't be your silver bullet: learn from your own success and read a lot, see sample applications, download open source solutions, listen your colleagues, drink a coffee and, after all, after some headaches, some day in the near future, you'll leverage these technologies (and many others).
EDIT
I'd like to add that a good way of using the know-how is creating a Visual Studio guidance pack, so you can automate a lot of tasks like creating managers, views, models and other things just in the way your team would do by hand.
For example, you can create a guidance pack for a WPF CRM-like application and you can automate module creation. When you want to add a new module, guidance pack starts a process which adds all the necessary classes to start development this new module, and it can create a sample form already associated with a navigation manager, controller or whatever (it's just an example).
Guidance pack and T4 would be both good tools for automating tedious or repetitive tasks in everyday's tasks:
http://msdn.microsoft.com/en-us/library/ff631854.aspx
http://msdn.microsoft.com/en-us/library/bb126445.aspx
I have been using WPF since 2008 and can honestly say to do it right and clean does take more time than the same thing in WinForms would take to develop. I have written a lot more WPF than Winforms. That being said - if I need a simple internal utility - it is ALWAYS Winforms. If I have something forward facing to a client - it is always WPF. Why? Winforms are cheap and dirty and you get a lot for free. What you don't get is the fit and polish that WPF can provide. The flexibility with WPF does come at a cost - but in the longer run it's worth it for public facing software.
Yes WPF is a hurdle but it also has rewards. You are on the right track with a design pattern such as MVVM. Sounds like you have not even gotten to the "rewards" of dependency properties or event bubbling. But the control over the UI is great. Almost everything is a content control. In forms I was always writing custom controls to get the UI I wanted. In WFP I have never had to write a custom control for UI and doubt I ever will. The syntax is new but it is compact - I rewrote a Form app in WPF and the WPF has 1/3 the lines and more features. Read a whole book on WPF just to get grounded - I like PRO WPF in C# 2010. You could also say LINQ is complex but man does it do a lot in just a few key strokes. WPF is not something you just pick up on the fly as you next application.

XAML Code Behind file and MVC

Does the code behind file have the same purpose as a Control class of MVC or the Boundary-Control-Entity Pattern?
I did some small projects with Silverlight and WPF, and most of the time I pretty much put the logic in the code behind file. Though with references to other classes. Not everything in the code behind.
What was/is the initial purpose of the code behind file and how do most of you use it?
Thanks,
Grant
The preferred design pattern for developing Silverlight applications is MVVM, in which the View Model is closer to taking over the role of a controller in MVC. When using the MVVM pattern, I'd only use the code behind of controls to implement UI-only (view-only) logic that has little to do with the data, such as performing animations and other special effects.
Originally, the code-behind file, in conjunction with data converters in WPF, served the same purpose as the code-behind in VB6, C#, VB.NET, what have you. It is primarily a place to put code that responds to UI events. However, in the case of WPF and Silverlight, coding in the code-behind file is potentially very messy and can easily lead to maintenance problems later on, if there is anything more than the simplest program to be implemented.
"Model-View-ViewModel" (MVVM) was conceived, I think, late in the development of WPF; Silverlight was conceived later than MVVM. Near as I can tell. Not every consultant I've heard talking about WPF or Silverlight is convinced that MVVM is "the preferred" design pattern, but it is a solid abstraction model.
WPF isn't as well tooled as WinForms, even today. This is part of what makes it potentially very messy with the potential maintenance problems. MVVM, as a design pattern, makes up for a lot of the drawbacks stemming from the immaturity of XAML and WPF/Silverlight as a user interface model, while bringing forward most of the tremendous advantages offered by XAML and WPF.
Summaries of MVVM are available here, here, and here. Josh Smith is a leading authority on the pattern, he sells a book called "Advanced MVVM" which I'm told is useful; I was able to implement some complex implementations without it, though.

wpf databinding testing

I'm in the process of learning WPF, where one of the strong suits is supposed to be data binding. When I do a win forms app, because I don't trust data binding much, I use what Fowler would call an assembler and just do it by hand, which makes it easy to test also.
I've read Jeremy Miller's blog enough to see he has issues with data binding too (even with wpf), and circumvents it, but I never did see a clear example of how he does it.
I do like what I see so far with wpf's rendering and layout capabilities, but I'm just not sure about the MS data binding technology. My question is does anyone have any reasons why data binding is so good in wpf you can easily separate concerns and test it, and if not, what is the basic idea you use as an alternative?
I don't want to speak for Jeremy, but I believe his beef with data binding is less about the binding itself, and more about how it results in hard to debug/test/maintain code. This is certainly true of WPF/SL when you include your bindings in XAML because they can break without you being aware of that until runtime (and maybe not even then). A nice fluent interface can make binding an absolute pleasure to write, debug, and maintain. It was one of my motivations for writing Truss.
However, doing your data binding in code can break the designer/developer collaboration. Blend doesn't execute code when designers open up a UserControl or whatever. Therefore, any bindings written as code will not be hooked up.
In an ideal world, we wouldn't be forced to choose between maintainability and designer collaboration. But that seems to be where things are at the moment.

Is there a performance hit for a Silverlight application while implementing MVVM pattern using Databinding?

I am implementing the Model-View-ViewModel (MVVM) pattern in one of the forms of my SL2 appication using INotifyPropertyChanged interface and TwoWay Databinding.
However I feel that due to this approach, my form behaves slightly sluggishly.
I just wanted to know whether using this approach is there any performance hit in such SL2 applications.
Thanks...
Sudeep
I have not noticed any slowdown. We are doing a LOT of binding to INotifyPropertyChanged ViewModels and the UI seems to be extremely responsive.
Sure, there will be a hit for data binding vs direct data access... but that hit is so small that the benefit you get from data binding makes the small hit inconsequential.
Something to remember: The data binding is happening in the UI. There isn't a lot of high intensity processing happening at that layer. In addition, the UI renders on a separate thread. Those two things together make for an experience that feels very responsive, in my opinion.
Erik asked if you have any Value Converters in place? I would ask the same thing. If so, are they doing a lot of work? In my experience with MVVM, value converters are rarely needed anymore. Just some food for thought.
I haven't noticed any slowdown. The Prism Reference Implementation, among many others, seems to be fast.
In fact, the binding system uses dependency properties. Just like the animation system. Part of the reason is that the values can be updated quickly by the framework.
Do you have any Value Converters in place?
We do a lot of MVVM with Prism and haven't noticed a performance hit. Quite the opposite - the app often demos faster than it's low-tech Windows counterpart.
Check as well in which places you need two way binding in which other just one time binding.

Should I use the Model-View-ViewModel (MVVM) pattern in Silverlight projects?

One challenge with Silverlight controls is that when properties are bound to code, they're no longer really editable in Blend. For example, if you've got a ListView that's populated from a data feed, there are no elements visible when you edit the control in Blend.
I've heard that the MVVM pattern, originated by the WPF development community, can also help with keeping Silverlight controls "blendable". I'm still wrapping my head around it, but here are some explanations:
http://www.nikhilk.net/Silverlight-ViewModel-Pattern.aspx
http://mark-dot-net.blogspot.com/2008/11/model-view-view-model-mvvm-in.html
http://www.ryankeeter.com/silverlight/silverlight-mvvm-pt-1-hello-world-style/
http://jonas.follesoe.no/YouCardRevisitedImplementingTheViewModelPattern.aspx
One potential downside is that the pattern requires additional classes, although not necessarily more code (as shown by the second link above). Thoughts?
I definitely think you should use the MVVM pattern for Silverlight applications - and one of the benefits of the pattern is that you can actually make your application really blendable through some simple techniques. I often refer to "blendability" as "design for designability" - that you use certain techniques to make sure your application looks great in Blend.
One of the techniques - like Torbjørn points out - is to use a dependency injection framework and supply different implementations of your external services depending on wether the code is being executed in Blend or in the Browser. So I configure my container to use a dummy data provider when the code is executing in Blend, and that way you get design time support for your list boxes, data grids etc.
The challenge is often how to set the DataContext declaratively - so I often end up using a service locator class a a "front end" to the IoC container. That way I can bind the data context to a property on the service locator.
Another technique is create some kind of ObjectDataSource control (non visual) that has two properties: Design Time DataContext and RunTime Data Context. The control does the job of detecting where is being executing, and then setting the Parent DataContext to the right object.
I'm not sure if I can answer your question, but I have foudn the article below very valuable. Jonas Follesø is using ninject to switch out his services when in design/blend mode. Very nice!
http://jonas.follesoe.no/YouCardRevisitedImplementingDependencyInjectionInSilverlight.aspx
I also agree with Jonas regarding MVVM with Silverlight. I do believe that MVP is also a good choice, but recently I have had time to try both MVP and MVVM with Silverlight and I am much happier with the results from MVVM. (Yep, I changed my mind the more I used MVVM). The VM abstracts the binding of the Model from the View (obviously) in MVVM which allows for more binding scenarios (at least cleaner ways to do them) than with MVP. That's just one aspect, though.
I'll be posting some examples of both MVP and MVVM with Silverlight on my site.
I've tried a few options and I'm settling on MVVM as the best choice for me. Blendability is an important point, and I also find the VM aspect intuitive for rigging up dynamic behaviors and procedural effects and animations (like Nikhil's Silverlight.FX). At one point I tried to avoid Blend altogether through fluent interfaces but am finding the coupling between UI and behavior too painful in the long-run. I want to design my UI in Blend and then add effects and other behaviors in code, this is proving to be the best pattern for me to follow so far.
I think many of us are waiting for the trailblazers to go ahead and create really good sample apps using MVVM in Silverlight (and WPF for that matter). There are a number of tricky areas such as the lack of ICommand in Silverlight, or the difficulty of interacting with animations starting and stopping only using data binding.
Its definitely a pattern to watch for the future though, and is worth trying out if you don't mind 'cheating' occasionally in the places where you can't quite figure it out.
I love the ViewModel pattern and highly recommend it. I have a couple of "getting started with ViewModel" types of posts on my blog.
ViewModel Pattern
HelloWorld.ViewModel
Binding Converts - VisibilityConverter
Silverlight Airlines with a ViewModel
I agree with Jonas. MVVM seems to be the model that works best for me (though John Papa thinks MVP makes more sense). I have an MSDN Article on this coming out in March that hopefully will answer the call for a good example.
BTW, I would like to see some cohesion in the MVVM Framework department. There isn't a good solution for a framework to follow yet. I like Jonas' (I think Jonas' is the FX Framework) but since its not WPF compatible it might not be the right choice for some.
I've been using MVVM lately on a couple of different Silverlight projects and it's been working really well, I would definitely recommend it. Jonas's post is a great place to start, I've recently blogged on my MVVM experiences too and created a really simple solution to demo the main touch points.
There's a very good Techdays 2010 video introduction to the MVVM pattern, clearly explained:
TechDays 2010: Understanding the Model-View-ViewModel pattern
Hanselminutes podcast by Laurent
For more complicated applications that require a higher degree of automated testing it definitely makes sense, and the move away from DependencyProperties to DataContext binding is a lot neater than it's ASP.NET counterpart.
The biggest challenge I've found with Silverlight is testing the actual UI (there's one commercial framework so far I think), and the huge tangle of event calls you get into when using WCF services (or the WebClient for that matter) with Silverlight.
I've always thought MVVM and PresntationModel http://martinfowler.com/eaaDev/PresentationModel.html are essentially the same thing. PresentationModel is a lot easier to say.
I've used it succesfully in java swing, windows forms, WPF and silverlight. If you think in terms of separation of concerns a Presentation Model makes a lot of sense. You have one class whose only concern is providing a Presentation friendly Model.It really doesn't matter what technology is used to show it on the screen. It might change some implementation details but splitting the concerns apart is a good idea no matter how you show the information.
Because of that separation you can easily write tests against your presentation model regardless of the view technology. So that's a plus.
With the Feb 2009 release of Prism v2 by P&P, even better support for MVVM now available for Silverlight and WPF. See microsoft.com/compositewpf for more details.
Take a look at my article about MVVM and Silverlight in real life projects and decide for yourself.
http://alexburtsev.wordpress.com/2011/03/05/mvvm-pattern-in-silverlight-and-wpf/

Resources