Lightweight View Models For WPF - wpf

I understand MVVM's usefulness in the context of a large team developing a shrink-wrapped application over a long period of time. But in the context of an internal LOB application, MVVM seems overkill and I'm having trouble swallowing the overhead of debugging declaritive databindings, jumping from layer to layer to layer, and extracting VM's that are barely more than the Model with a command or two. Even accepting that overhead, still leaves me with the holes in MVVM like dialogs. A few things I've considered is:
Binding directly to the Model and do old-school event handlers for form interaction
Binding a user control or window to itself, effectively using the code behind as the VM.
Include a property in my VM to reference the related view.
Make ViewModel's subclasses of a View.
The above items and their combinations address some problems but not all. I do realize that I might sacrifice testability. What other technical (not conceptual like SOC) issues will I run into using one or more of these practices?

I always use MVVM when coding in WPF or Silverlight, even for small single-page apps. It makes it much easier to test and maintain in the long run, and I find it faster to create apps with it than without it
I don't mind taking some shortcuts in smaller apps, such as binding to the Model instead of exposing the Model's properties in the ViewModel, or defining my View in a DataTemplate instead of a UserControl, or using Window's Dialogs in my ViewModels, but I would never consider doing a WPF or Silverlight app without MVVM.
If you want, I have an example of a very simple app done with MVVM here

Code re-usability comes to mind. Properly written VM's could be re-used behind Silverlight or WP7 implementations down the road.

Related

How to design a data model to be usable across different application frameworks?

I have a WPF GUI application based on MVVM design and data binding. Now, I want to reuse the core code (i.e. the data model) in a Windows service, or a console UI app, or a WinForms app.
Is such a design reasonable? If yes, what are the pitfalls?
Or should I make a standalone data model instead, and interface WPF via wrappers?
UPDATE:
Sorry, I should have been more precise. Let me clarify: I don't doubt the very modularity thing =) My concern boils down to having my current DataModel implement INotifyPropertyChanged, use DispatcherTimers, etc. -- all that non-GUI but still WPF stuff. The model's business logic is based on it.
Is this (non-GUI WPF) design acceptable for reuse in the aforementioned cases, or should I abstract further, until no references to WPF would be required at all?
Yes, this is perfectly acceptable and most of the time it is desired!
When you build an MVVM app, it should be in at least 3 formal layers:
Presentation WPF, UI, xaml, behaviors. All that stuff. Not reusable
Application The view models and structure that supports your application rules. All that stuff. Not intended for reuse
Foundation Database access, business objects. Domain specific algorithms. Ideally this bit should be reusable anywhere
The foundation layer is the clever bit. This is where the meat in your application sandwich is. It makes perfect sense for this to be totally agnostic of UI technology. WPF, winforms, ASP. It shouldn't even need a UI.
Edit for question update:
Removing all references to WPF is hard because sometimes you need a CollectionViewSource on your view models for grouping/filtering of results. That is a WPF class.
It is very tempting to view your seperation-of-concerns as 'just dont reference wpf' and that helps but it can make life difficult. Instead, try to be disciplined with the type of behaviors you are putting in. If you find yourself writing 'clever' (domain) code on a view model, shift it to the foundation layer as a business object method or extension. Similarly, if you find yourself implementing IValueConverter often, perhaps you should make better use of view models.
One thing is for sure, your foundation layer should never, ever, ever reference WPF.
Such a design is very reasonable! You can create a portable C# library for all .NET technologies including WPF, WinRT, ASP MVC, etc which can contain your models. Obviously you'll need to wrap these portable models into a viewmodel anyway, but IPropertyChanged is implemented in all XAML flavors.

WPF & silverlight development process

What would be the application development process for WPF applications and silverlight application?
Like how many tiers the application is divided into and how they communicate with each other. And what steps are followed during development like design , then business logic layer.
How the data base is accessed can Linq be used or data sets are better option?
I would suggest that you start out using the WPF Application Framework. Your "tiers" should be something along the lines of:
Business "Model" logic (database, LinqToSQL/EntityFramework is great with WPF)
Your "View" which is your WPF/Silverlight controls
Your "ViewModel" which binds the Logic to your View, passing change notifications anduser interactions.
I would do these steps in order. Assuming step 1 is mostly complete since it's not really unique to WPF/Silverlight, make an interesting UI but don't tie it to your model quite yet. Then study up on ViewModels. ViewModels, strictly bound and not accessed in code behind, will give you the best results.
If you're already familiar with C#/.NET, I would also strongly suggest you check out this excellent screencast showing you how to retrofit an application to following the "Model, View, ViewModel" architecture.
The process would be the same as for any other application; that is, design an architecture to suit your requirements! However, within your actual WPF/Silverlight code, you might want to look at the Model-View-Viewmodel architecture.
MVVM is a pattern that is typically used to structure the code behind a WPF UI, though it doesn't dictate how you access your data or define your business logic. The MVVM code would sit on top of your business/data code and provide an abstraction that's suitable for the UI to work with.
This question isn't really about WPF or Silverlight as they are just UIs. The architecture isn't dictated by whether you use Silverlight, WPF or something else.
For example (and not limited to this scenario), if you are using a classic n-tier architecture, you could continue to do so while using a Silverlight front end.

What MVVM framework is Good For?

i know some Mvvm Frameworks that introduced in this thread
please describe or give me link for that what are them useful for?
not information about MVVM about MVVM Framework.
thanks :)
i want to know :
What Is MVVM Framework?
I think your question is not really precise. As far as I understand, you ask for the features of each framework?!
You can find detailed information here and here. However, at least one of these links has already been given in the thread you mentioned...
EDIT:
Basically, an MVVM framework is a collection of classes which are commonly used in applications utilising the MVVM (Model-View-ViewModel) pattern. This may include messaging systems to communicate between independent parts of a software, dependency injection techniques, base classes for ViewModels, project/class templates, validation mechanisms, commonly used commands, techniques for displaying dialog boxes, and so on...
To completely understand such a framework, you will have to understand the MVVM pattern first. Because only then (or even only after you did your first MVVM project) you will have an understanding of the problems and/or challenges of this pattern.
To use Mvvm framework just simply follow below steps:
You have a model and a view-model with the same name.
View-models are not supposed to be wrappers around models. The job of a view-model is to broker requests for external services such as the loading and saving of data. The data itself, as well as validation and most of the business logic, should be in the models.
I can’t emphasize this enough. Whenever you create a view-model that wraps a model by delegation you introduce a huge hole in your API. Specially, anything with a direct reference to the model can change a property in such a way that the view-model and thus the UI are never notified. Likewise, any changes to calculated fields in the model won’t be propagated back to the view-model.
You have a view and a view-model with the same name.
Ideally view-models are agnostic to the screens they are used by. This is especially true in a WPF application where multiple windows may be sharing the same instance of a view-model.
For smaller applications such you may only need a single view-model for the whole application. For larger applications you may need one for the main functionality and one for each secondary aspect such as configuration management.
You have no code behind.
In absolute terms code behind is neither a good nor a bad thing. It is merely a place to put logic that is specific to a single view or control. So when I see a view with no code-behind at all I immediately check for the following mistakes:
Does the view-model touch specific controls by name?
Is the view-model being given access to controls via a command parameter?
Is EventToCommand or another leaky behavior being used in place of simple event handler?
EventToCommand from MVVM Light is especially bad because it will prevent controls from being garbage collected after they are removed from the screen.
View-models are listening to property changed notifications
If a model has a longer life-span then the view-model that listens to its events then you probably have a memory leak. Unlike views which have an unloaded event, view-models don’t have a good story for life-cycle management. So if they attach an event to a model that may out-last them then the view-model will be leaked.

Why MVVM and what are it's core benefits? [duplicate]

This question already has answers here:
Why use MVVM? [closed]
(13 answers)
Closed 2 years ago.
Why we go for MVVM over MVC or MVP while dealing with WPF?
What extra benefit we get by using this?
Edit:
To be honest , today I had an interview and I have been asked this question. I answered like INotifyPropertyChanged , ICommand,IValue Convertor.. but he was not satisfied. Henceforth I have put up this question
Thanks in advance
I'll point you to a particularly useful video by Jason Dolinger.
Coming from a WinForms world, implementing any MVX style pattern seemed like more hassle than it was worth but after working with WPF for a couple of years now, I can honestly say that I wouldn't consider anything less. The whole paradigm is supported out-of-the-box.
First off, the key benefit is enabling true separation between the view and model. What that means in real terms is that if/when your model needs to change, it can without the view needing to and vice-versa.
Secondly, while your model may contain all the data you might need in your view, you may want to abstract that data in such a way that your model doesn't support. For example, say your model contains a date property. In the model it can exist solely as a DateTime object but your view might want to present it in a completely different way. Without the viewmodel you'd either have to duplicate the property in the model to support the view or modify the property which could seriously obfuscate the 'model'.
You can also use a viewmodel to aggregate parts of your model that exist in separate classes/libraries to facilitate a more fluent interface for the view to deal with. It's very unlikely that you'll want to work with data in your code in the same way that a user will want to or will want that data presented to them.
On top of that, you get support for automatic two-way data binding between the view and viewmodel.
There really is a whole bunch of extra stuff that I could bang on about but Jason say's it far better that I could so my advice is watch the video. After a few days of working like this, you'll wonder how you ever got by without it.
Good luck.
These are mine specific to MVVM
Increases the "Blendability" of your views (ability to use Expression Blend to design views). This enables a separation of responsibilities on teams that are lucky enough to have a designer and a programmer... each can work independent of the other.
"Lookless" view logic. Views are agnostic from the code that runs behind them, enabling the same view logic to be reused across multiple views or have a view easily retooled or replaced. Seperates concerns between "behavior" and "style".
No duplicated code to update views. In code-behind you will see a lot of calls to "myLabel.Text = newValue" sprinkled everywhere. With MVVM you can be assured the view is updated appropriately just by setting the underlying property and all view side-effects thereof.
Testability. Since your logic is completely agnostic of your view (no "myLabel.Text" references), unit testing is made easy. You can test the behavior of a ViewModel without involving its view. This also enabled test-driven development of view behavior, which is almost impossible using code-behind.
The other two patterns are really sort of separate in terms of the concerns they address. You can use MVVM with MVP and MVC (most good samples out there do some form of this).
In fact, MVP (w/ a Passive View, rather than a Supervising Controller) is really just a variant of MVVM, in my opinion.
WPF has better databinding than any other UI framework, which MVVM would be unruly without
MVVM provides unit testability and excellent view-agnosticism, which make it a good thing to use
Baked in support for ICommand and INotifyPropertyChanged are the two biggest benefits. Using MVVM makes it really easy to wire up the commands and plug data into the WPF UI. Things just work.
I personnaly see MVVM not as a benefit, but as an obligation for those who want to use WPF cool features.
WPF is very very heavily built with data binding at the core, to enable separation of UI from Model. But the way data binding is technically done in WPF is somewhat special, as it's tied to classes like:
DependencyProperty
INotifyPropertyChanged
ObservableCollection
Because of this you just can't really write a model the way you want using standard .NET technology. For example, the WPF TreeView is almost impossible to use w/o using data binding and templates. You just can't populate it simply like you would from a generic model in Winforms for example. It must be bound to a hierarchical model using ObservableCollection to represent a node's children.
So let's say V represents the XAML code and it's code-behind counterpart (so it's tied to WPF as a technology), and let's say M represents your model (so it's not tied to WPF UI technology in anyway).
Well, you'll never have this working properly under WPF with only these V & M.
You must add something between the two. Something that's WPF-compatible and understands your model. Something that speaks DependencyProperty, ObservableCollection and INotifyPropertyChanged. That's what's called VM.
As a side note, an alternative to MVVM is to build a V & M (w/o VM plumbing) combination with M being WPF-compatible but still with a reasonable UI independency. Historically, ObservableCollection was in the WindowsBase.dll assembly (that was shipped with WPF), so it really looked weird to bind a generic model to something tied to a UI technology. It's been moved back to System.dll since. Even then, it's sometimes hard to keep a pure VM model w/o tweaking the M specifically for WPF...
The ability of XAML code to databind, as well as the existance of triggers will break the MVP and MVC Patterns.

Is Databinding a good way to connect a view to a model

I am thinking about the design of a WPF or Silverlight application. I am planning to use MVC (or another such design pattern)
Witch ever of the design patterns I choose, I need to connect to view to the model (or presenter) – is databinding a good way of doing this?
(In the past with WinForms applications I have found that Databinding give lots of problem in the long run and does not fulfil its promise. It is the same with WPF and Siverlight?)
Yes, you should definitely definitely use data binding. While WinForms and ASP.NET were always a struggle to get anything data bound consistently and in a maintainable manner, Silverlight and WPF are built from the ground up for data binding pleasure.
Binding is two-way so you don't have to write tedious plumbing code to move data in and out of your model. Just implement INotifable and away you go.
Converters allow you to write code to handle the way things are bound if the defaults aren't working. Using converters (which are dead-simple to write) you can bind booleans to visibility settings, strings to images, integers to background colors, and so on. The sky's the limit.
Patterns such as MVVM are perfect for the rich data-binding support in WPF and Silverlight. MVVM lets you have the best of both worlds: loosely coupled code together with data binding.
Element binding lets you bind the property one element to the property of another element. Together with converters, this gives you impressive power to do things like bind the current position of a slider control to the selected index of a list control. Both ways.
Deep binding means you can bind to the property of a property of your model. Not that you always should, but you can.
Binding is almost magical in its dynamic-ness. As long as your model continues to support the same bound properties, binding will continue to work even if the static type of the model changes. Binding is also crazy flexible. You can bind to collections, interfaces, complex objects, (almost) anything you like.
DataContexts can be used to set up data-binding at a page, control, or container level. Children of the container then inherit the same data-context. This lets you bind once at the page level and then use binding paths for the rest of the page.
I recommend you take a look at the Model-View ViewModel (MVVM) pattern. Here is a very good video you should take a look at: Jason Dolinger on Model-View-ViewModel. Two-way data binding in WPF is very powerful.
be it WPF or Adobe Flex or Winforms , Databinding will always give issues when the application becomes complex. I would prefer to avoid data binding for easier debugging. But data binding runs all around WPF that we can't avoid. Doing data binding in XAML takes away control from the developer.
I think , if we keep the data binding in the code , its much easier to debug.
Imagine , MVVM without data binding , it will look messy. A design pattern that takes advantage of technology is good but a design that is totally dependent on a particular feature is a disaster.
Data binding in WPF goes far beyond what you could achieve in Winforms. It is intrinsic to the platform and prevalent throughout. I would argue you can't understand WPF without understanding its data binding system.
It's not without its pitfalls, to be sure. Broken bindings are often not as obvious as you may like, but improvements have been made to help you identify and flag these issues.

Resources