Public Methods or subscribe to View events - winforms

I have written a MVP project where the View is a WinForm that implements my IView interface.
I am in the process of reviewing the code, improving it where I can and would like to ask your thoughts regarding how the view and presenter interact. Which of the following is best practice in your opinion?
Expose methods of the presenter class for the view to use. (i.e make them public).
Have the presenter listen to events raised by the View class.
For example, my MVP uses a service that communicates via a serialport. To connect to the remote device my view calls the public Presenter method Connect() which then calls the appropriate service methods.
Would it be better practice to raise a Connect() event and have the presenter listen for it?

Generally I work so that the view is dependant on the presenter and the presenter is dependant on the model. This means the same model can be used by multiple presenters and the same presenter can be used my multiple views (different UI layouts, or Winforms vs Web etc). To facilitate this the view calls public methods on the presenter and listens to events from the presenter to say when data has changed.
For an example of why you may want to work this way imagine an interface that has two views one for a beginner user and one for an expert, with the beginner view showing a subset of the expert commands. If the same presenter is used for both of these views then the beginner view will need to expose events for all the expert commands since the presenter needs them to be there so it can bind to them - even though they will never be triggered. On the other hand the presenter can expose methods for all of the expert options and the beginner view just never calls them, this means that neither the view nor the presenter are implementing unused functionality.

The guideline I would follow here is - "Public methods in presenter should be parameterless. View object should access only parameterless methods of presenter. Another option is view can define events to which the presenter can subscribe. Either way, there should be no parameter passing." . Open to sugeestions and comments.

Related

Prism and MVVM databinding from modules to main shell datacontext

Have some experience with WPF and databinding, but completely new to PRISM and MVVM.
I'm working on Prism application where I have a shell and multiple modules.
In my previous WPF application I had a single window datacontext (with all objects I need) which I could then simply databind from any usercontrol inside my window.
In the context of the Prism, what is the proper way to have a single datacontext, let's we call it ShellViewModel and then for all modules to bind to its' objects and properties? So if there is a change in one property in ShellViewModel which is caused by one module, another module can detected that by databinding and then maybe trigger a style?
Probably there is a simple way to do this but I'm new to PRISM and MVVM and completely confused how we can do properly bindings especially when there are multiple modules involved?
Also any source code and examples would be great.
If you have a single source of data, make it available to all your view models as a service.
Register it as a singleton, so that all view models get the same instance. If you need the service to push updates to the view models, make it implement INotifyPropertyChanged and let the view models observe that (done best through a PropertyObserver).
Remember that the view model is the data context of the view, and that it should only communicate data and events between the view and the data source a.k.a. model, but should not own data itself.

Ambiguous between Microsoft Sample and WPF Rules

I thought we should have no reference from View to ViewModel in MVVM Pattern. but just saw an MVVM Sample from code.msdn.microsoft in which ViewModel implements new Window and shows it;
By using MVVM-Light toolkit you use Messenger to Call or Open new Window and Still keep Separate the View and ViewModel form each other. Is it right to reference the View in ViewModel? Or it is wrong;
Do you suggest to call Views Directly from ViewModel for large(or medium) projects?
http://code.msdn.microsoft.com/windowsdesktop/Easy-MVVM-Examples-fb8c409f
YAGNI.
Level of effort and complexity.
MVVM is just a pattern. A pattern you don't have to follow. Any little tool I write for my own use just uses a model, a viewmodel, and a view. The viewmodel exposes all properties I need for the view by INotifyPropertyChanged. The data is moved back and forth from viewmodel to model manually using ViewModel.FromModel(model) syntax. I don't bind to my models. I only use the model when saving/loading data; I don't hang onto it. My views are generated using dataTemplates and dataTemplateSelectors. If I have a property that should change the layout I expose that on the viewmodel and use a selector. Otherwise, I have a datatemplate for every viewmodel object. And it just works.
I call this a form of MVVM, even though it doesn't any toolkit or the exact MVVM pattern that Microsoft describes.
I would personally implement a service to drive commands from the viewmodel to generate new views and hookup the viewmodel. But that's because I have MVC experience, and I think generating views is easier to do using the MVC pattern, whereas desktop views work better using the MVVM pattern.
All my views are composed with contentControls. Setting the content is setting the viewmodel.
So I use a hybrid.
If your software isn't so complex to need the complete Microsoft endorsed MVVM pattern, why create the overhead code IMO. YAGNI.
IMO, having a strong reference from the ViewModel to the View has 2 problems:
It breaks the testability of your ViewModel code. This means you won't be able to Unit Test your code so easily, and if you do you'll have to account for Dispatcher issues and the like.
It makes your ViewModels dependent on WPF assemblies and types. This means you won't be able to literally copy and paste your ViewModels into other applications or platforms such as Xamarin.Android or the like
If none of these are important to you, I don't see any reason why you wouldn't. Not doing so creates additional overhead in your code, by having to implement WindowManagers and whatnot.

Wpf: datatemplates and event subscription management

Sometimes a Domain Model object with a business logic (DDD) when calling a method an event is fired.
In my situation, a viewmodel (for a given view) encapsulates the domain object and needs to register and react on those domain events (i must use events because that same domain object can be managed by many loosely coupled views along with their viewmodels).
I also need to unregister to those events when that particular context is hidden.
I can handle this register/unregister/dispose in parallel with show/hide/dispose of that view using databinding, programmatically or whatever if the scenario keeps simple enough...
The problem comes when visualization logic comes with DataTemplates.
How can I know when that datatemplate becomes hidden so that I can unregister my events? is it there a better way with wpf to handle this, instead of adding more events?
What is the best practice to handle this scenario in a good MVVM approach?
edit: ok, the problem is structural. sometimes choices made inside the project has forced us to work in an atypical manner... in a good mvvm approach this problem should not happen
I'd be careful in making the ViewModel dependent on the View for making things right.
So what I would do is provide a property (Show? Visible? Open?) on the ViewModel that has a TwoWay binding with the View so the ViewModel can monitor the property.

Is there any reason to make POCOs into Model objects?

If I am generating POCO objects from EntityFramework, and using these to go to/from the WCF server, is there any reason to create client-side Models for the Views & ViewModels to use instead of just using the POCOs directly?
Almost all the MVVM examples I have looked at bind straight to the object returned from the WCF service. Is this good practice? Are there arguments that can be made for actually mapping the POCO to a Model and having the Views/ViewModels working with the Model object instead of the POCO?
The main reason I could think of is validation, however since the EF POCOs are partial classes, they can be expanded on to include validation.
EDIT
Most answers so far have brought up INotifyPropertyChanged as the main reason to build a separate Model. Does your answer change if you are using Self-Tracking entities instead of POCOs which already includes INotifyPropertyChanged? STEs are also partial classes which can be expanded upon to include validation.
Validation is the main reason not to bind directly to a POCO. In addition, if the POCO doesn't already implement INotifyPropertyChanged and other required interfaces, the experience working with the object on the WPF side may be less desirable, and implementing a ViewModel to wrap this makes sense.
Providing a ViewModel to wrap your POCO allows you to encapsulate the logic into ICommand implementations as well as implement required interfaces cleanly.
I disagree only slightly with Reed (an unusual circumstance to be sure). I would NOT implement a ViewModel to wrap the POCO. I would implement a Model class to wrap the POCO and expose the Models to the ViewModel via a Service layer.
The ViewModel's primary job is to appropriately present Model data to the View and react to its requests. The architecture I'm working on for this looks like so:
1 ViewModel for each View
The ViewModel calls a Data Service layer object to retrieve Model instances (not to be confused with a WCF service)
The Data Service layer issues the appropriate CRUD requests to the backend (this uses WCF, RIA, or RESTful Services for Silverlight but could be ADO.NET or EF directly for WPF).
The Data Service uses the returned POCOs to create Model objects.
Model objects wrap the POCO object and implement INotifyPropertyChanged. Model objects enforce business rules.
I'm still working through the details but I will be publishing something more concrete in the near future.
My Models accept a WCF object which exposes those properties which I wish to use in my ViewModel. I can then also extend the object as needed. My properties point to the WCF object's property and when I have to send the object back to the WCF service, I don't have to do any more work. The models inherit INotifyPropertyChanged and INotifyDataErrorInfo which the DTOs (mentioned here as POCOs) will not have. Your business logic / validaton exists in your Silverlight application and not in your WCF Service.
The View binds to the ViewModel which has a Model (or an observable collection of Models). The Models have a WFCObject which is a DTO (mentioned here as POCO). I use my ViewModel to communicate with the service, MVVM Light has the models communicate with the service / provider - which I don't like.
Bind to EF POCOs if you want to do simple CRUD or you want to make something fast.
Otherwise, your server-side models will tend to be very closely related to the database, which changes very slowly, as compared to user interface. For less trivial UI, you'll find yourself putting more and more kludges just to fit your database model into UI (or otherwise, which is even worse).
Also, there are performance issues (e.g. would you like to transmit whole entity when for UI you need only couple of properties?), and maintenance issues (e.g. if you would like to validate premium customer's order quite differently from ordinary one).
See also http://ayende.com/Blog/archive/2010/08/06/data-access-is-contextual-a-generic-approach-will-fail.aspx
Rachel's POCO's are just dumb objects generated by EF and used for transport (DTO). Therefore, they shouldn't have other things cluttering up their domain. This is a very nice way of designing your code because it decouples any client-side requirements from those on the server-side. That's why MVVM exists - to extend the MVC model incorporating those concerns.
There is no reason you can't bind to them in your views as long as you are not modifying them directly. You can add functionality to them by adding a partial class but I wouldn't even do that. In that case you should follow the MVVM design tenants and separate those into model objects that serve your needs in the client. This will be quite automated once you hook up INotifyPropertyChanged events to notify your views.

use of mvvm pattern in wpf application

i am new to wpf and i am designing a client-server application using wpf for UI
i have one view - view model, datalist and communication model
my view and view model will form one user control
following are my doubts:
if i keep my datalist inside viewmodel, how other view model can access it
if i keep my datalist in application so that any view can access it , whether my view model will be able to update it through binding
it will be good design if my view model calls my communication model directly or should i keep a wraper class in between.
thanx
sarika
You should think about using a repository pattern to access your list of items. Your viewmodels should work against an abstraction of this repository (e.g. IPeopleRepository), and you should pass a concrete implementation of this repository into your viewmodel via injection (e.g. through constructor injection). Your concrete implementation can call your communication model to retrieve the list of items.
Typically, your repository will return a collection type which is not specific to WPF. You'll probably want to wrap this in an ObservableCollection on your viewmodel, so that the UI is notified of changes to the collection.
Whether each viewmodel retrieves a new reference to this collection, or if they all access the same collection, will depend on your use case, but as long as the collection is exposed as a property on your DataContext (typically your viewmodel), then you'll be able to bind to the collection to display and update it from the view.

Resources