I am currently learning how to make advanced usage of WPF via the Prism (Composite WPF) project.
I watch many videos and examples and the demo application StockTraderRI makes me ask this question:
What is the exact role of each of the following part?
- SomethingService: Ok, this is something to manage data
- SomethingView: Ok, this is what’s displayed
- SomethingPresentationModel: Ok, this contains data and commands for the view to bind to (equivalent to a ViewModel).
- SomethingPresenter: I don’t really understand it’s usage
- SomethingController: Don’t understand too
I saw that a Presenter and a Controller are not necessary but I would like to understand why they are here. Can someone tell me their role and when to use them?
I had exactly the same problem when I first went through Prism.
Controllersare basically for logic that spans an entire module, whereasPresentersare for logic that is specific to aView.For example, a
Presenterwould respond to a command that results in a button in the view being disabled. AControllerwould respond to a command that results in theView(andPresenter) being changed entirely, or perhaps loading a different View/Presenter in a different region in the module’s shell.Edit: As for when to use them, you can skip the
Controllerentirely if you have no need for the orchestration mentioned above. The simplest application will just have a:Module: registers the view/presenter into theRegionPresenter: responds to commands from the view and modifies theViewModel.ViewModel: adapter betweenPresenterandViewthat implementsINotifyPropertyChangedView: binds toViewModeland displays UIEdit: As for Presenter vs ViewModel, most of your logic should be in your Presenter. Think of your ViewModel as housing the logic for your view, but the Presenter as dealing with the consequences of interacting with the view.
For example, the user clicks the “Search” button in your
View. This triggers anICommand, which is handled by yourPresenter. ThePresenterbegins the search and sets theViewModel.IsSearchingproperty, which fires the PropertyChanged notification forCanSearch.CanSearchis a readonly property that is based on several other properties (eg.IsSearchEnabled && !IsSearching). The “Search” button in theViewhas itsEnabledproperty bound toCanSearch.