View and ViewModel getting too large - wpf

While adding extra functionality to the main view I have in my application, I've realized that the amount of code will soon become a problem (currently around 600 lines of code in my viewmodel and I still have plenty to add).
I've been looking around for articles on how to split/design your view into smaller components, but I haven't found a satisfying solution. One person suggested using child viewmodels but that presented with other problems (dependency between the viewmodels).
I've thought of using user controls, but there is nothing on the View that I use on other Views so it kind of defeats the purpose of user controls.
What is a correct approach in this situation?
Thanks,
Adrian

If you want to split a view into component parts, then you need to do view composition. If you are building an MVVM app, then you should really be using an MVVM framework. Something like Caliburn.Micro makes view composition incredibly easy.
There doesn't necessarily have to be dependencies between the view models, they should only know about what they need in order to produce their view. This could be a subset of the business object that the parent view model contains. As the parent view model will have references to all of the child view models, it can pass the relevant parts of the business object to them at the point of their construction.

I would agree with using Caliburn Micro.
However, to play devil's advocate you could split out your ViewModel File into separate files (same class name) and use the partial keyword before the class keyword. Its generally tidier and one step-away (non-breaking precursor) from breaking-up into separate classes.

I also agree Caliburn.Micro is a good solution for splitting your application in smaller components.
In Caliburn.Micro the communication between viewmodels is based on the Event aggregator pattern.
This makes a loose coupling between viewmodels

Splitting up is not ideal.
It looks as if the Caliburn toolkit focuses on events, whereas my application largely relies on ICommand implementations.
To me, the first encounter with Caliburn.Micro has been unsatisfactory.
The setup appeared to be tailored to VS2010 - which sounded promissing to me - because I do have VS2010 pro. But I got lost in the setup's of Silverlight.
Compared to toolkits like Prism it lacks the ease of an start.
It just takes to much time to switch now.
I use my own MVVM paradigm, it is less abstract than the Caliburn, it integrates multilanguage support everywhere, and it just faces one acceptable problem of some sources getting too big because of the nature of the Binding/DataContext paradigm.
For this problem I accept that "partial class" is a solution - even though I know there is a more elegant solution available.
In the heat of my work, I cannot change to another toolkit.
So I gently wait for Microsoft to allow for more flexibility around that Binding/DataContext paradigm.
It may be the case that Caliburn shows more intelligence allocating a viewmodel to some item. Does it ? (I think it does.)
What might be another option is to define a custom (xaml useable) object that triggers a custom allocator which control is to be allocated to which viewmodel. How about that ?

Related

Are the advantages of Model-View-ViewModel (MVVM) pattern worth the overhead?

The question is stated in the subject: are the advantages of Model-View-ViewModel (MVVM) pattern worth the overhead?
In many cases, implementing the view model involves quite significant overhead of duplicating the Model properties and sometimes synchronization between Model and ViewModel data members. For example, currently in Silverlight 4 & WCF RIA, View Models are not generated (if the developer follows the MVVM pattern, it is up to him to create the view models, often duplicating the corresponding Model's properties at ViewModel, that do nothing significant but refer to Model as the storage).
Why not extending the Model class, providing additional properties to make it easy to be consumed by the View instead?
Why not extending the Model class, providing additional properties to make it easy to be consumed by the View instead?
Effectively that is what the PresentationModel is for. Which MVVM is strongly based on. The difference is that the ViewModel is the model for the view and not the model for the data. So you are concerned around more how the view behaves with the data.
If you have a simple UI that all it does is present the model then I would suggest expose the Model on a property of the ViewModel and bind to that. Make sure though the model does implement INotifyPropertyChanged etc.
The power of the ViewModel is when you have things to do in response to a user action. The ViewModel can then support Commands, calling out to services and validation and thus leaving the Model as a data container
Why not extending the Model class, providing additional properties to make it easy to be consumed by the View instead?
In the simple cases, this is all the ViewModel is doing - wrapping up the Model so that its extended in a way that's consumable by the View. If your Model can be bound directly, you're welcome to do so.
That being said, there is more to the ViewModel layer than just wrapping the model - this is also where the application specific logic - ie: the application's plumbing, will occur. Something has to make the requests from the Model classes correctly and compose together the logic.
If you are concerned about extra work, you can always create a ViewModelBase (INotifyPropertyChanged , Errors/Validation, generic stuff) to be inherited by your ViewModel, it will minimize things that you think may cost you time to replicate. And also, Silverlight/Wpf provides us with binding which greatly reduces our coding, besides the fact that XAML also does that by providing functionalities through markup. Besides that you can further the design by using screens, controllers, etc.
For me, I do not see any "overhead" with regards to using MVVM; if there were, it'd be worth it. It properly deals with the Separation of Concerns. It provides a good platform for development especially in teams where people may take care of different aspects of the application without affecting other team members codes (especially between developers and designers).
Hope this helps
Benefits of MVVM
Reduced complexity.
Isolation of Designing and Development.
Dependency injection.
Major advantage is when you have a Well MVVM structured Windows Phone application and want to develop same for Windows Metro Desktop, Only thing u want to concentarte on design as the same view model can be used as it is.
Hope it helps.

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.

Confusion regarding MVVM pattern and dynamic loading of XAML in GUI

Well this question relates to MVVM pattern and i could good and fast answers on this forum so I thought to ask and clear the confusions i had about the pattern.
I am quite new to MVVM approach. I appreciate the pattern and understand the principals behind it. Maybe I have not worked that much with the pattern that’s why there are a few confusions.
If there is a scenario in which I want to load few parts of my WPF page dynamically with XAML and still want to be compliant with MVVM approach.
The confusion is:
Where the logic of loading a view dynamically with XAML reside.
Whether I should have a single ViewModel for my WPF page or each seperate part have its own viewmodel with interactions with other viewmodel classes.
What if I had to build control tree displayed on the GUI using C# code in the codebehind itself.
For the controls created using code should I do the commandbindings in the codebehind of the view itself.
Where the logic for loading goes is something not really addressed by the pattern itself. There's an interesting blog post about this by Ward Bell. There's any number of ways to skin this cat, and they're all compatible with MVVM. Not really the answer you're looking for, I know, but it's honest :). Check out Ward's blog post... you'll get a much more in depth discussion of this topic.
As for whether or not to have a single VM for the page, or one for each control, that just depends. Generally, I have one for the page. If there's some portion that reusable elsewhere, I break it out into a user control with it's own VM, which means we have a VM within a VM. I don't agree with rockeye on this one. There isn't a one-to-one relationship between V-VM-M. You're Models are designed according to business needs, with NO regard to presentation at all. You're ViewModels are designed according to your presentation needs, and may encapsulate more than one Model. In fact, it's very common for them to encapsulate many models.
Like rockeye, I don't understand your last question.
I am also quite new to mvvm, but i will try to answer :
Where the logic of loading a view dynamically with XAML reside
If you mean "how can i show the view associated with my business object?", IMHO, you don't have to care about this. Usually, your VMs have corresponding views. With dataTemplate, you use only VM in the code but Views are displayed automatically.
2 Whether i should have a single ViewModel for my WPF page or each seperate part have its own viewmodel with interactions with other viewmodel classes
It seems you have a top-bottom approach. I see the mvvm more as bottom-up : models (business objects) -> ViewModels -> Views. Every model should have its own ViewModel and view. So you can't have a whole WPF page in a viewModel unless you model represents a page.
3 What if i had to build control tree displayed on the GUI using C# code in the codebehind itself. For the controls created using code should i do the commandbindings in the codebehind of the view itself.
Don't understand. I think you may take a look at dataTemplate, it might be helpfull.

Should I Keep Business Objects Separate from the UI in WPF?

WPF's view model oriented way of doing things makes it very tempting to just use business objects in the UI. Have you seen any issues with this? Why or why wouldn't you do this?
The guidance from Microsoft's product teams (e.g., that's what the Blend team is using) is the Model-View-ViewModel architecture, a variant of the popular MVC pattern. A good starting point is http://blogs.msdn.com/johngossman/archive/2005/10/08/478683.aspx. There are also good articles by Dr. WPF on this topic.
Essentially, they advocate to create a ViewModel layer which uses binding-friendly business objects, such as ObservableCollection and the like.
Also, if you might eventually move to Silverlight 2, you might want to keep the business objects out of the UI layer so you can swap out UI technology (until WPF and Silverlight become source-code compatible).
I guess I see it in a different light. I try to keep as much out of the UI as possible so I can use whichever UI presentation I need (ie. web, WPF, WinForms). The more business logic in the presentation layer, the more you may have to rewrite later if you migrate towards a different UI.
It's not a problem having business objects in the UI, as long as all you're doing is viewing them. In other words, if you want to change the properties of one, or delete one, or create a new one, you should be sending a message to the controller, presenter, or whatever to do that; and the results should then be updated in the view.
What you shouldn't do is use the ToString method of your objects (or any other methods or properties on your objects) to affect how they'll appear in the view. You should use DataTemplates to represent the view of your objects. If you need a more complex representation, you can use an IValueConverter to change the object into its visual representation.
Not being a WPF guru, I can't be sure, but the usual reason for separating your M, V and C is so you can test the controller independent of the view, and the other way around.
Nothing stopping you, of course, but it should be a lot more testable (ie, unit tests) if it's separate. The MVP pattern, which is usually the one that MS promotes, is more geared around the presenter (ie, your WPF form) having more control, and thats fine too....
Depending on your application architecture or the on the way you are planning to reuse your components and objects, you can choose a certain degree of independence from the user interface (in this case WPF).
Here is a sample of my experience:
I've worked with WPF just a little, on
a relatively small project, where the
business layer was already defined,
and we just needed to create a user
interface. Of course, the interface
had defined it's own rules and objects
that it was working with, and because
the application was defined just for
UX we have chosen to create our own
specific objects, mostly by extending
DependencyObject (mainly for Data
Binding purposes).
Some people may argue that it's not ok
to use dependency objects because they
not are serializable (actually they
are - to XAML), they bring a
dependency to WPF (the
System.Windows namespace), and some
other arguments. Also,
DependencyObjects support other
options, like attached properties
and dependency properties. Others
might like to use for example
INotifyPropertyChanged if it
makes sense, and others might say that
all of these patterns don't belong in
other layer than UI.
(If you want to learn more there are
some good WPF data binding
articles in the MSDN library,
including best practices for
perfomance and for user interface)
It's kind of bad that Microsoft has chosen to add some of the goodies to the System.Windows namespace, instead of, for example, to the System.ComponentModel where in my opinion they might have been more useful (by providing all of these important patterns not only to WPF but to the .NET Framework).
Of course this is just the beginning and many of us know that the thing will be evolving to the right direction in the end. (With the risk of going off-topic: Take silverlight 2.0 framework for example. It was a rushed release, with some of the objects in the WPF model missing and some not in their natural place.)
In the end, everything depends on you, your programming style, your architectural decisions and your knowledge of the technology.
If it seems more natural to do it in a way, than by the book, think why you should and why should you not before taking any decision!

Resources