As I am further digging into MVVM and MVVM-light I recognized, that there is no MVVM-light provided base class for models.
But from my understanding, messaging and raising notifications could also happen in a model. At least in communication between models I would find that messaging would come in very handy.
So I just decided to derive my Model from ViewModelBase, even though some of the properties (like the design time ones) will be unused.
But the more I am looking at this, the more I think I have missed something. Is it considered "bad practice" to derive my Models from ViewModelBase?
And is it ok to use Messaging for Model communication?
Derive your view-model classes from whatever you like... MVVM-light offers the VieWModelBase to provide an implementation of ICleanUp - which is good for managing the life-cycle of ViewModel objects. My own choice has been to implement all scaffolding for Property Change notifications in a base class, then derive from that for model classes. About the only strong suggestions I have regarding model classes are:
Once size doesn't fit all. How you store your data may be different from how you interact with data, and ViewModel objects should be geared towards supporting interaction, not storage, and if you need to interact with the same data (Model) in two very different ways, then design two different ViewModels to support these different interactions.
Do use attributes (a la System.ComponentModel) to annotate the models. You can get a lot of your validation work done this way - and validation feedback is the responsibility of the presentation layer (View + ViewModel), not the problem domain (i.e. the Model).
Really good ViewModel classes are also usually stateless enough that they can be recycled/reused within a single user interaction, such that large data lists can be virtualized (WPF supports virtualization) to save RAM.
Remember DRY (Do Not Repeat Yourself), KISS (Keep It Simple, Stupid!) and YAGNI (You ain't gonna need it) - are the principles you should keep in mind above any academic design principles. I've litereally wasted weeks on a WPF app implementing academically perfect MVC/MVVM patterns, only to find that they detracted form the overall understandability of the finished solution. So... keep it simple! :)
I would take a look at the EventAggregator in the Composite Application Library. The answer in this post has a good description of it. Jeremy Miller's post goes into a bit more detail.
Related
I am developing a C# MVVM WPF app and have problems to decide whether I should use the message mediator pattern or simple INotifyPropertyChanged for my UI 'live' Model change notifications. The problem in particular is that my model represents a graph with lots of 'live' objects that all have properties where different viewmodels will be interested in the changes at some point. I have about 3-5 viewmodels active that need notification of model changes. Some changes might be nested deep inside the models 'grandchildren'.
I tried to compare both messaging techniques, mediator pattern and INotifyPropertyChanged, and think that the mediator is better suited for change notifications between different modules/systems. My viewmodels definitely need the initial values of the model upon initialization and then change notifications afterwards. INotifyPropertyChanged seems to be the optimal choice in my case, but I am a bit skeptic, because I think lots of nameof(e.PropertyName) switch cases are not very elegant. Are there better alternatives for this problem?
As is typical for such cases, you could have both ways. You will obviously not be able to avoid using INotifyPropertyChanged because this is the WPF way of handling MVVM-based Data Binding, so all your view-models will be at least basic implementations of this interface.
I suspect that you might simply need both. I would not suggest using the INotifyPropertyChanged-based pattern inside your model. The reason this interface was created was to base the observer pattern on actual property names as strings. This was pretty much a "one-way street", as XAML, the typical "design" language supporting WPF, is parsed in a "stringly" manner, leaving few efficient alternatives. In my humble opinion, there is almost no reason that you would want to force notifications throughout your model to be as weakly-typed (stringly-typed, in fact) as this scenario, so I would suggest avoiding INotifyPropertyChanged if you have a relatively voluminous Domain Model.
Messaging would probably be the way to go, maintaining strong-typing with message type registrations and whatnot, unless you would like to consider other alternatives, such as simple C# events, or even combine both. While at it, try to stick and adhere to hierarchy and encapsulation as strongly as possible but also as weakly as practical*.
(*I mean, if some of your Domain objects reach multiple nesting levels, then, occasionally, it may be more practical to bypass hierarchy and let, for example, grand-grandchildren send messages of their own, instead of notifying their parents' parents through events, and letting these parents' parents then send the corresponding notification messages. In typical OOP programming, compromises are constantly weighted against practicality and time availability).
By learning so much about the MVVM patterns I find it very useful and solves many problems we encounter on a daily.
But I dont understand how it goes along with OOP. OOP always dictates us to be encapsulated, to care about the hiding of fields (initialize them first in the constructor and no further access to set them) but if we define almost every model class with getter/setter properties it broke the rules of OOP.
So how does it goes along? Is it ok to define many get/set class in a real MVVM application?
Thanks,
Jacob
Hi I dont think it breaks the OOP concept. We expose the data members via public properties. So data hiding is there, user of the class does not know setting which property is going to change which data behind the scene. In the setter of the properties we can have validation logic and any chain of responsible methods/properties that can change the state of the class. So encapsulation and data hiding is there.
Thanks
There is no versus here, MVVM is an OOP design pattern.
Properties don't break OOP principles, it's an application of the encapsulation principle; i.e. control how an object data is acceded or modified.
Encapsulation don't tell us to avoid data modifications in objects, it tells us to be careful with it, to control it.
More infos on that here
As per the above answers, MVVM does not break OOP it embraces it. Ideally where you can, you should reduce the surface area of your software by limiting the read/write nature and encapsulating cohesive sets of properties into their own objects. This can lead you to having some parts of your model that are immutable. However, it is very difficult to follow a Immutable data model (DDD/Functional Programming concept) in MVVM if you have editing requirements.
This might be a long list of questions but please bear with me. I started building LOB applications with WPF, PRISM, CODE FIRST and SQL CE, and after my first application (or attempt) I have many questions, so to begin with:
Where should business logic go, in the model or in a BLL layer just above the domain layer ?
Should view models receive references to repositories or should repositories be used only by the domain model objects ?
To put the second question in another way, what sort of objects should be given to view models ?
I use the same view model in display (in a data grid for example) and for editing in a form but that causes a lot of trouble, is there a better way to do this without code duplication ?
The biggest problem I have faced was that I always organized my view models in hierarchical relationships without allowing the children in the hierarchy to obtain references to their parents, and since the views bound to those children and invoked methods that caused the addition of objects to the repositories I couldn't find a way to notify the parents of the changes to the those repos. so the bound views could be updated, I have seen some people solve this using events but I don't like this solution and I would like to know if there is a better way to do it ?
Can anyone point to an example of building real life LOB applications using the technologies mentioned above, at least not examples that use VB .NET or WCF (I want local databases).
I'm developing a LOB app right now, with WPF, Entity Framework Code First and SQL CE 4.0 with a local database. I'm not using PRISM, but I'm using MEF as IoC with my own implementation.
So far, I recommend that you use the benefits of Code-First approach and implement as much business logic in your domain classes as possible. Also implement INPC in them. If you don't you'll end up having all your properties duplicated in your ViewModels, which is nonsense. There is no rule that says that the model should be dumb (although some people tend to think so), but a dumb model just makes the ViewModels more tedious to work with.
No clear recommendation here without knowing more of your project, but common sense: try to stick to best practices unless they start coming in your way. "Perfect" is often the enemy of "good".
Let the ViewModel get whatever they need (single model objects, collections, etc.) to serve your views. Often the simpler solution is easier to maintain in the long term.
I don't quite understand what you mean with this... I use my ViewModels several times if possible, but think that a ViewModel's function is to serve a View, if you are having trouble trying to get one VM to work for several Views, it's probable that you need to divide it into two different VM. Just gather all the common properties and methods in a base class and inherit from it as you need.
There are some loose-coupled ways for the VMs to communicate with each other. I'm using MVVM Light Messenger class for such things, but I understand that PRISM provides a similar functionality. It's not a sin to reference the parent from the child if you don't abuse it. I have a ViewModelBase<T> and the child have a reference for their parent pointing to the base class and specifying the T type, a good balance between hard and loose reference so far.
If someone points you to such an example, let me know! Actually, working with a local database should be simpler. In my case I'm using a singleton context (which a lot of people seem to loathe) but since this is a local app, with a single user and no threading complications a singleton context makes my life much easier. I'm still waiting to find a real good reason not to do so with this conditions.
PS: some people will probably downvote your question because... it is not ONE question, and it opens room for a lot of debate. If it gets closed, try the chat.
Hope this helps you, regards!
I have an example with a bunch of logic in my GUI class (winforms). I am going to refactor that so that there is no logic in the gui and a separate class holds all the logic.
What is that pattern? Say I had a form class called AddAddressForm, what would you call the associated file that holds the logic? AddAddressMediator (doesn't quite fit that pattern), if I was doing WPF I would call it the ViewModel (but I am not).
Sounds something like model-view-controller without the model part.
I don't think its called anything. I've tried doing that sort of thing in the past with Windows Forms, but unfortunately it didn't really work:
For each form I had another class called something like MyFormLogic that supposedly contained all of my logic for the form, with the form itself just containing a load of methods and events for manipulating the form (things like an AddButtonClicked event, and a AllItems collection property)
It seemed like a brilliant idea at the time (Yay easy unit testing!), but what actually happened is the MyFormLogic class became just as big and messy as before, and now I had a whole lot of extra pointless code exposing the extra methods events in my actual form class. (Also creating an instance of forms was a pain)
I'd recommend that instead you work on refactoring out as much logic as possible into lots of smaller classes that do 1 thing, rather than 1 extra class which deals with all forms logic (Its difficult to explain what I mean without some examples)
By the example given , it seems that your object shares some kind of common data.
Look at the Flyweight Pattern then.
I believe it is called Model-View-Presenter pattern. although it is commonly used in asp.net, it should be applied to WinForm as well.
http://msdn.microsoft.com/en-us/magazine/cc188690.aspx
Martin Fowler splits original MVP pattern into 2 patterns , Supervising Controller and Passive View, But I still like its original name , MVP.
it depends type of logic , say you have Conditonal Logic and you create different object from it , so seprating this in a new class will be pointing to Factory Method.
2- If you have complex algorithms in your class and you seprate it another class/s , you most probably using Strategy Pattern.
lot of other combinations also possible.
It's Model-View-Controller (MVC). In your example, the Model is the Address, the View is the dialog, and the Controller just mediates events from the dialog to the Address object.
Note: you may omit the Controller for really simple situations, but don't if you ever want automated unit-tests; the separation (via interfaces) will pay off.
I believe this is called Humble View.
For more details and different takes on it, see the Humble View section of the GUI Architectures page on martinfowler.com.
What you describe is still the Model-View-ViewModel pattern, which isn't specific to WPF. The core tenet is that the ViewModel contains state and logic, and the View constantly synchronizes itself with the ViewModel. This is nice and easy with WPF bindings, but they aren't a prerequisite; any stateful UI can utilize MVVM. The Forms flavor of the pattern can get quite wordy on the view side.
Sounds like your basic separation of concerns by breaking out the view and functionality into different files. Not really sure if it really falls under any sort of pattern per say, but it does remind me of web forms a liitle bit with the views and code behinds.
My name is Jesús from Spain, I'm a .NET developer and I just discovered this great web few days ago.
I have some questions about the MVVM pattern and I will be glad if you can answer them.
I started using WPF three months ago and I've learned the MVP pattern.
MVP is so good because you can structure the application so well.
I started seeing MVVM everywhere, but everyone is using the pattern by his own method.
Every blogger is talking about MVVM in their WPF's blogs but every implementation is distinct.
I'm focused now with the implementations that use the MVVM toolkit on CodePlex, but I have questions and I can't find too much information.
I think that MVVM is a variation of MVP.
With MVP every view has a presenter that does the view's job.
In MVVM it's the same thing but using commands whenever you can.
I also saw that if you need an event, it's like with MVP; delegating the event to the presenter / View-Model, that is if it's not a job for the view (such as updating the UI).
On the other hand, the View-Model doesn't has a View reference so I have to play harder with data-bindings.
You have to use the DelegateCommands (that are the same thing as RelayCommands, right?).
Uhm... more questions... Is it safe to use the same View-Model with two views / user-controls?
Oh... I ran into a problem yesterday when I was playing MVVM.
I created a CommandReference of my command for the key-binding thing and I assigned this reference to the command property of my button, well, the CanExecuted worked the first time but it didn't update the IsEnabled property when the CanExecuted was true. I fixed it by binding the command directly to the button and not using the reference. The question is: Why some code is linking the reference to the objects and why other code is binding the command directly?
What things related with MVVM should I learn? (I saw something called attached behaviors yesterday but I don't know what is that).
I'm rewriting a note tacking app that I developed using MVP but now with the MVVM. I will replace the events with commands (using the DelegateCommand), eliminate the views references on the View-Model and I think that's all because the examples that I saw of MVVM is much like MVP.
Well, I will appreciate if you point me to all the misunderstandings that I have with this pattern.
Thank you and in the future I will help the next MVVM novices :)
Wow, I'm going to try to answer as many of your questions, that don't involve a specific technology or framework, as possible... sorry if I miss some (bullet points would help)
MVVM is not necessarily a variation of MVP. MVP itself is an ambiguous, loaded term. Martin Fowler did it justice by splitting it into two patterns. MVVM stands on its own, but shares some concepts with the MVP patterns. Like all UI patterns, it seeks to separate view logic from business logic as much as possible. What the MVVM does that is different from MVP is it creates a model purely for the purpose of presentation (or a presentation model). This is different than how MVP patterns solve the separation problem.
Passive View - With the passive view, the view never sees the model.
Supervising Controller - MVVM is much closer to the Supervising Controller pattern than to the Passive View. The only real difference here could be that the MVVM explicitly creates a model just for the view (hence the term "View Model")
The ViewModel doesn't have a reference to the view, because it serves as a model for the data of the view. This is an appropriate abstraction. If it also referenced the view, you would have a two-way dependency which would create additional coupling. Also, the ViewModel itself doesn't have a real reason to be aware of the View. Its only job is to abstract the model (the actual business model) from the view.
DelegateCommands vs. RelayCommands - I believe you're getting technology specific here, so I can't really answer that one well.
You should not design a ViewModel for more than one view. This only creates coplexity inasmuch as if you change a view, you will have to investigate which ViewModels might be affected and change those. This could possibly lead to a cascade effect. Your behavior should be in the business model, not the ViewModel, so the ViewModel need only contain translation and event handling logic.
It would be a good idea, however, to have a 1:1 ratio of ViewModel to UserControl, since UserControls are supposed to be able to act as autonomous units on your screen.
As for the other technology specific questions, sorry, I have no answer. I can suggest, however, that you carefully read the links I included for the Passive View, Supervising Controller, and Presentation Model. The provide some context to UI patterns, and are technology neutral.
It's important to keep in mind that, while MVVM is suited to solving problems posed by adopting WPF, it is not a technology specific pattern. If you dive too deeply into a specific implementation without understanding the underlying philosophy, you could make some very big mistakes early on, and only discover them after it's too late. Unfortunately, MVVM is not a well documented pattern, and you are right when you stated that everyone has their own idea of what it is.
It's not a revolutionary pattern (it has been around for years under different names), but the data binding of WPF makes it a viable solution now, and so it's enjoying newfound popularity. It's a good pattern, but it's not doctrine. Approach every "dictate" you're faced with with the appropriate amount of skepticism.
EDIT
#micahtan is right when stating that data bind is a very important piece in WPF. I stated that WPF's data binding enables the MVVM solution, but the binding itself is very powerful, which is why adoption of MVVM is growing faster than the literature surrounding it.
You don't actually have to use the RelayCommand. All you really need to do is implement the ICommand interface on an object. In the SoapBox Core framework I defined an interface called ICommandControl and all button ViewModels, etc. implement that. There's also an AbstractCommandControl class you can derive from to implement it.