WPF / MVVM - Where do the ViewModels go? - wpf

I am kind of new to the whole MVVM pattern, and am trying to wrap my head around it. What I am currently trying to figure out is: in a well structured solution where do the ViewModels live?
Currently my design looks something like this (sort of):
Application (The view)
DomainSpecificCode (ClassLibrary)
Gateways (ClassLibrary)
If I were to add on another type of view (for instance ASP.NET or Silverlight), where would be the best place for the ViewModels to exist?

ViewModels should go in the Application layer because they tend to be technology-specific.
For example you may want to databind a View attribute to a particular color based on the state of the ViewModel. However, Color is implemented by different types on Windows Forms, ASP.NET and WPF, so you wouldn't be able to reuse the ViewModel accross different technologies.
If you add new Applications, you must also provide new ViewModels.

Recently, I built a MVVM Desktop application that had 2 flavors:
WPF Document Base GUI
Console application
Both exe were using the same view models, one was WPF and the other one was not.
I was able to split my solution into the following projects (libraries/exe):
non-project related re-usable code (called Common)
project models + persistence
project view models
WPF application + views
Console application
It was amazingly easy to build the console application version just by using the View Models. The console application code had less than 200 lines of code, and was basically loading the ProjectViewModel and doing operations on it.

This article describes a concrete Architecture for WPF MVVM Applications.
Layers:
Presentation Layer: Views
Application Layer: ViewModels
Domain Layer: Domain specific code

Related

I wanna develop a WPF application with XAML on my desktop and then convert it as a windows phone application. Can I do that?

I am new to this. But I wanna develop a DESKTOP APPLICATION using WPF, XAML and then convert it into a windows phone application. But i dont have a clear idea about it... Can you please help
To implement MVVM, you typically create both the model and the view
model in a Portable Class Library project, because a Portable Class
Library project cannot reference a non-portable project. The model and
view model can be in the same project or in separate projects. If you
use separate projects, add a reference from the view model project to
the model project.
After you compile the model and view model projects, you reference
those assemblies in the app that contains the view. If the view
interacts only with the view model, you only have to reference the
assembly that contains the view model.
Inspiring from above, I believe that the user interface in WPF and WP cannot be the same. XAML would change a little. So,since you haven't begun, the approach could be building the core (Classes,Business logic, Functionalities...) using Portable Class Library project. and two UIs : one for WPF and the other for WP.

How to properly make a silverlight application?

I am starting on a silverlight application and my MainPage is getting to be fairly large. I am not sure how to properly make a silverlight app in terms of object orientation or separating things into multiple xaml pages. Is it normal to have all of your application in the MainPage? For large elements such as a drawing tool, do people make custom controls and then add them in the main page?
I'm not really sure how to set this up and was hoping someone would shed some light on what the normal architecture of a silverlight app is.
As Steve B suggested you should look into MVVM and use that basic pattern to separate your application into views, models and view-models which bridge the gap between the view and the underlying models. The pattern is not difficult and works very well for data binding in WPF and SilverLight.
To manage the complexity of your main page use multiple UserControls to keep different parts of the UI in different files.

ObserverableCollection UI pattern in WinForms

In many ways I think of using the MVC pattern in WinForms, but I'd like to know if it's possible to bind controls with objects using the ObservableCollection type? If it's purely for WPF, what other alternatives are out there?
To put it into perspective, we're building a system which has business logic that I'd like to control the UI with, instead of making customizations for each requirement or workflow on the UI itself. We have around a few hundred potential forms which I'd like to start designing with the pattern in mind.
We're also building web interfaces for most of the processes, but in reality they're just watered-down versions of the Forms. If I can use the same framework which I can just bind to on the web form that would be awesome.
Thanks
What ObservableCollection does is that it implements INotifyPropertyChange and each control in WPF has the possibility to listen for it's bound data to raise the event from INotifyPropertyChange. You can read more here about why you can't use ObservableCollection they way you want to in WinForms.
Another way is to use the Model-View-Presenter pattern:
This pattern can also be used in ASP.NET.
There's an MSDN Magazine Article on: "Better Web Forms with the MVP Pattern" that I think you should look into. And here is an introduction to how you use MVP-pattern in asp.net.

Silverlight design pattern for performance - very rich client UI

Following on from this initial investigations on Silverlight architectures, I have some new requirements to consider.
We expect our Silverlight client UI to be graphically heavy, with a GIS interface, multiple charts, gauges and datagrids arranged in a Widget style fashion. New widgets will be dynamically generated by the user.
Suppose a user wanted to dynamically create a chart widget from an existing datagrid widget pre-populated with data. It appears to me that if we were using a MVVM pattern with the view model on the server, this would result in an unnecessary call back home when the required data is already located in the client.
Now obviously the server needs to know about this new chart widget on the client, but how do I create the widget in the client first (with the existing client side data) and then notify the server about the new changes?
In our intranet, the network link between the client and the server is not particularly good so performance is critical.
It seems from my initial research that the common Silverlight architecture patterns call for as much of the business logic to be pushed back to the server. I understand the reasoning for this, but fear that it will really hurt the usability of our application.
Are there particular design patterns that address this issue? Is this 'client-binding' supported within MVVM, Prism or other common Silverlight architectures?
Is there a more formal name for what I am attempting to describe?
I am quite new to both Silverlight and design patterns such as MVVM, so please correct me if any of my assumptions are wrong.
The MVVM pattern is for separation of concerns. It does not define how or where you get your data.
The model, is data. It can be data you get from any arbitrary source. In silverlight, the most common way to get data is via a webservice (SOAP/REST). But your model can be any data from anywhere.
The view model is just another class that probably implements the INotifyPropertyChanged interface (So you bindings can automatically be updated). This class is an abstraction for your view's data. Let's pretend it has a string property called "FirstName".
The view is your UI (A user control in SL). You setup your bindings here to your ViewModel. IE, .
The view and view model are put together when you set your views DataContext. myView.DataContext = new MyViewModel(); There are many ways to set the DataContext depending how you want to set things up.
Prism is just a framework to help write decoupled applications in WPF/SL. It does not enforce the usage of any UI pattern (ie, MVP/MVC/MVVM). What it does come with is a bunch of classes can be used to assist with MVVM development, such as a mediator (EventAgggregator) and a dependency injection container (Unity).
So enough digressing...What I would suggest, is you have a web service where you can get all your data. You SL app would get that data (most likey the web services will be called in the view model). That data now exists on the client side and you can setup your VM to bind to this data in your view.

UI Design Pattern for Windows Forms (like MVVM for WPF)

MVVM is most commonly used with WPF because it is perfectly suited for it. But what about Windows Forms? Is there an established and commonly used approach / design pattern like this for Windows Forms too? One that works explicitly well with Windows Forms? Is there a book or an article that describes this well? Maybe MVP or MVC based?
I have tried MVP and it seems to work great with windows forms too.
This book has an example of windows forms with MVP pattern (sample payroll application). The application is not that complex but will give you an idea about how to go about creating it.
Agile Principles, Patterns, and Practices in C#...
You can get the source code at
Source Code
EDIT:
There are two variations of the MVP pattern
(a) Passive view and (b) supervising controller
For complex databinding scenarios I prefer to go with the Supervising controller pattern.
In supervising controller pattern the databinding responsibility rest with the view. So,for treeview/datagrid this should be in the respective views, only view agnostic logic should moved on to the presenter.
I'll recommend having a look at the following MVP framework
MVC# - An MVP framework
Don't go by the name (it's an MVP framework).
Simple winforms MVP video
Winforms - MVP
An example of dealing with dropdown list
MVP - DropDownList
Simple treeview binding example (poor man's binding). You can add any treeview specific logic in BindTree().
Below is the code snippet.... not tested, directly keyed in from thought....
public interface IYourView
{
void BindTree(Model model);
}
public class YourView : System.Windows.Forms, IYourView
{
private Presenter presenter;
public YourView()
{
presenter = new YourPresenter(this);
}
public override OnLoad()
{
presenter.OnLoad();
}
public void BindTree(Model model)
{
// Binding logic goes here....
}
}
public class YourPresenter
{
private IYourView view;
public YourPresenter(IYourView view)
{
this.view = view;
}
public void OnLoad()
{
// Get data from service.... or whatever soruce
Model model = service.GetData(...);
view.BindTree(model);
}
}
As it has already said, i always worked in a MVP pattern when using Winforms. But the design pattern you will use not mean you will use right. There is loads of anti-pattern attached to MVP.
If you want to starts everything in a good manner, you have to use the framework for building smart client. So i will recommend to use that design and practices: Smart Client Software Factory http://www.codeplex.com/smartclient
You have a discussion here about the current smart client frameworks : http://codebetter.com/blogs/glenn.block/archive/2008/05/10/prism-cab-and-winforms-futures.aspx
PS: I like this post on the MVP anti-patterns: http://blog.mattwynne.net/2007/06/13/mvp-smells/
Hope this helps
The Model-View-ViewModel (MVVM) Pattern is a design pattern. Per definition a design pattern shows a common solution in the object-oriented world and this solution can be applied in various platforms (WPF, WinForms, Java Swing, etc.). I agree that MVVM is best used with WPF because it leverages the strong binding capabilities. However, Windows Forms supports data binding as well.
The WAF Windows Forms Adapter shows how to apply the MVVM Pattern in a Windows Forms application.
I have written about a variation of MVP/MVVM design patterns called MVP-VM, which is a tailor made solution for winforms applications that require full testing coverage and use data binding as main mechanism for keeping the presentation updated with model data.
MVVM for .NET Winforms
MVVM (Model View View Model)
introduces similar approach for
separating the presentation from the
data in an environment that empowers
data binding (WPF). Since .NET
framework 2.0 already offers advanced
data binding infrastructure that also
allows design time binding of
application objects - the ‘View Model’
entity can fit quite well in MVP based
environment.
I asked this same question to two of my techies co-workers: is MVVM for WindowsForms possible? Both gave me the exact same answer: "No way! WindowsForms is missing the rich bindings of WPF and Silverlight (OneTime, OneWay, TwoWay, OnewayToSource) and it is also missing the TypeConverters."
Screen Activator Pattern for WindowsForms - you can find it here, ported from Caliburn.Micro by jagui
Rich Bindings and TypeConverters - Truss by Kent Boogaart, does it in an UI independent way
Commands - WPF Application Framework (WAF) has a WafWinFormsAdapter project that takes care of some MVVM stuff namely commands
Again, can we have MVVM for WinForms?
Yes we can. We have all the pieces. We just have to glue them together.
I believe that MVP is a pattern well-suited to WinForms development - as is partly evidenced by it's use in CAB - Microsoft's framework for WinForms.
I use MVP in WinForms to extract code out of the View - because I can't test the View code. And also to enable code that needs to be reused (or is duplicated) to stay out of the View where it can't be shared.
I can refer to my own project where I use the MVP pattern ExceptionReporter.NET. Though I'm sure I don't use it perfectly.
You mentioned MVVM working for WPF - I think the reason for that is because of strong data-binding support. If you were not using data-binding in WPF (and it's certainly not compulsory) then you could choose MVP. The point being that MVP is a strong choice for any client-side application. And possibly a 'better' choice, even in WPF, if you plan on sharing code between projects that aren't WPF.
For more evidence of the value of using MVP in WinForms see Boodhoo's video presentation on using MVP:
http://www.bestechvideos.com/2008/06/29/dnrtv-show-14-jean-paul-boodhoo-on-model-view-presenter
And an MSDN article by the same author at http://msdn.microsoft.com/en-us/magazine/cc188690.aspx
The BindTree method seems a little
flawed to me. Suddenly the the View
knows abou the Model. Is that a good
thing? There must be tons of poeple
being confronted with these kind of
problems. I am surprised that there
aren't any books about it. Since there
are books about everything in the .NET
world.
These Design not about hiding the model rather precisely defining the interactions between the different layers of the applications. You can change the backend completely and as long as you pass a Model through Bindtree your UI will continue to work.
Now class Model may be a poor choice of a name in the example that Rajesh gives. It can be TreeData, or RecordsData. However you define it, it has what you need to using the binding mechanism of Winforms to bind a specific control to the underlying data.
The best site to browse for this kind of material is here. Martin Fowler has collected a variety of useful UI design pattern and enterprise design patterns.
Again the key to this is the use of interfaces to precisely define how each layer interact with each other.
In my own application (a CAD/CAM applications used to run metal cutting machines) my structure looks like this.
Forms implementing form interfaces
UIDLL with views implementing view
interfaces that interact with forms
through the form interface. The
specific views register themselves
with UIViewDLL Views executes Command Objects found
in command libraries that interact
with the Model.
Command libraries; lists of
commands implementing ICommand.
The command that interact with
views do so through the interfaces
exposed in UIViewDLL.
UIViewDLL; exposes the View Interfaces
used by the commands.
Model; the classes and collection that
make up core data structures of my
application. For me these are things
like material, cuttingpaths, shape,
sheets, torches, etc.
Utility; a DLL that has commonly used
utility classes used by my company
that span different application. For
example complex math functions.
You can use Enterprise Architecture, Patterns and Practices as the starting point, although they are slightly dated.
Under General Guidance there is Application Architecture for .NET: Designing Applications and Services, which is a good introduction to .NET ways and layered N-tier application.
alt text http://i.msdn.microsoft.com/ms954595.f00aa01%28en-us%2CMSDN.10%29.gif
For more formal "patterns", there is Enterprise Solution Patterns Using Microsoft .NET.
(source: microsoft.com)
To name a few,
Model-View-Controller
Intercepting Filter
Three-Layered Services Application
The first good explanation of UI design patterns I read was in Jeremy Miller's blog - Building Your Own CAB. It describes the common patterns - Passive View, MVP, etc. and addresses some of the ways you might implement them in C#.
You can try MugenMvvmToolkit that allows to use a "pure MVVM" for WinForms.
Due to the fact that it supports bindings on all platforms, all of the native binding features available for WPF platform available on all platforms (include WinForms).

Resources