MVVM: IView vs. databinding - mvvm

I am reading about MVVM in order to adopt this across my presentation layers' views. Ideally I would like to use the same approach for WinForms, ASP.NET and SL.
I came across 2 distinct approaches and I would like to gather opinions in these (and possibly others):
The 'View with interface' and where the View is databound to the ViewModel
'View with interface'
In this approach we have an interface IView that contains:
- Set/Get properties for the typical field values
- Events for actions that happen on the View
The way this works is by a concrete implementation of the IView being injected into the ViewModel. The ViewModel then wires up the
events. It also then 'pushes' and pulls field values via the properties. It is also aware of what happens on the View by means of
the events. Controls can be activated and deactivated through the IView properties.
Concrete implementations of the view is easy in WinForms, not sure about the other technologies and the 'Blendability' in SL.
public interface IMyView
{
event EventHandler SomeActionClicked;
Boolean CanEditField1 { get;set; }
string Field1 { get;set; }
}
public class MyConcreteView: Form,IMyView
{
public event EventHandler SomeActionClicked;
public Boolean CanEditField1
{
get { return edtField1.Enabled; }
set { edtField1.Enabled = value; }
}
public string Field1
{
get { return edtField1.Text; }
set { edtField1.Text = value; }
}
private void btnAction_Click(object sender,EventArgs e)
{
SomeActionClicked(sender,e);
}
}
public class ViewModel
{
public ViewModel(IMyView view)
{
this.view = view;
view.SomeActionClicked += SomeActionHandler;
}
private void SomeActionHandler(object sender,EventArgs e)
{
view.CanEditField = !view.CanEditField; // Or whatever 'state' the ViewModel or Model is
view.Field1 = DateTime.Now.ToString(...);
}
private IMyView view;
}
Databound View
The other approach is a ViewModel that has several properties that reflect the Model (data/field values, UI control states, etc.
The View then uses databinding to 'present' the field values (Model) in the UI controls on the View. The ViewModel also controls
UI control states through properties being databound to. Actions in the View is fed to the ViewModel through methods in the
ViewModel that are hooked to.
Any (non-apparent) pros & cons to each of these methods?

Maybe you would actually only need the view as a "presenter" of the properties in winforms, while in SL all the wiring up is done trough the xaml, that would require less boiler plate.
So keep your view models in a common code base, while the view is specific to winforms.
For ASP.NET, those viewmodel events are not so sweet to hook up, unless you go for ugly oldschool webforms controls and postbacks.
I dont really see the difference between the two approaches, both would work with SL.
Keep it simple.

Related

Best practice MVVM navigation using Master Detail page?

I want to follow the MVVM pattern as much as possible, but I don't know if I am doing the navigation quite well. Note that I am using a MasterDetail page and I want to maintain the Master page, changing only the Detail side when I navigate.
Here is the way I navigate from my ViewModel. In this example, from ViewModelOne to ViewModelTwo:
public class ViewModelOne : ViewModelBase
{
private void GoToViewTwo()
{
var viewTwo = new ViewTwo(new ViewModelTwo());
((MasterView)Application.Current.MainPage).NavigateToPage(viewTwo);
}
}
MasterView implementation:
public class MasterView : MasterDetailPage
{
public void NavigateToPage(Page page)
{
Detail = new NavigationPage(page);
IsPresented = false;
}
}
ViewTwo implementation:
public partial class ViewTwo : PageBase
{
public MenuView(ViewModelTwo vm)
: base(vm)
{
InitializeComponent();
}
}
PageBase implementation:
public class PageBase : ContentPage
{
public PageBase(ViewModelBase vmb)
{
this.BindingContext = vmb;
}
}
Is this the best approach (and best performance) for do the navigation? When I do some navigations, the app starts to run slower and maybe there is something I am not doing fine.
Is this the best approach for do the navigation showing always a MasterDetail page?
Thanks.
I think you're certainly on the right track, however there are a few issues here:
Firstly, you should not be instantiating Views in your view model. As soon as your View Model becomes aware of the view, then you've pretty much broken the pattern.
var viewTwo = new ViewTwo(new ViewModelTwo());
Your view creation should be the responsibility of the master view. In fact, you don't even need to worry about creating views, as you can use a DataTemplate for that. I'll explain that later.
Firstly, we need to separate your View Models from the Views, here is what I propose:
You'll need some kind of base class or interface for your view models in order to keep things generic, you'll see why in a moment. Let's start out with a simple example:
public abstract class ViewModel : INotifyPropertyChanged
{
public event EventHandler OnClosed;
public event EventHandler OnOpened;
//Don't forget to implement INotifyPropertyChanged.
public bool IsDisplayed { get; private set; }
public void Open()
{
IsDisplayed = true;
//TODO: Raise the OnOpened event (Might be a better idea to put it in the IsDisplayed getter.
}
public void Close()
{
IsDisplayed = false;
//TODO: Raise the OnClosed event.
}
}
This of course is a very simple base view model, you can extend on this later, the main reason for this is to allow you to create a master view model which will be responsible for displaying your current page. Here's a simple example of a master view model:
public class MasterViewModel : INotifyPropertyChanged
{
//Don't forget to implement INotifyPropertyChanged.
public ViewModel CurrentPage { get; private set; }
public MasterViewModel()
{
//This is just an example of how to set the current page.
//You might want to use a command instead.
CurrentPage = new MovieViewModel();
}
//TODO: Some other master view model functionality, like exiting the application.
}
Please note that INotifyPropertyChanged would probably be better in some kind of base class, instead of having to re-implement the same code over and over.
Now the MasterViewModel is pretty simple, it just holds the current page, however the purpose of having the master is to allow for application level code to be executed, like closing the app, that way you're keeping this logic away from your other view models.
Right, now onto the good stuff.
Your detail has a relationship to it's parent, therefore it would make sense to say that it is the responsibility of the parent to manage it. In this case, your master-detail view model would look something like this:
public class MovieViewModel : ViewModel
{
protected PickGenreViewModel ChildViewModel { get; private set; }
public MovieViewModel()
{
ChildViewModel = new PickGenreViewModel();
//TODO: Perhaps subscribe to the closed event?
}
//Just an example but an important thing to note is that
//this method is protected because it's the MovieViewModel's
//responsibility to manage it's child view model.
protected void PickAGenre()
{
ChildViewModel.Open();
}
//TODO: Other view model functionality.
}
So, now we've got some kind of view model structure here, I bet you're asking "What about the views?", well, that's where the DataTemplate comes in.
In WPF, it's possible to assign a view to a Type, for example, you can assign the MovieView to the MovieViewModel in XAML, like this:
xmlns:Views="clr-namespace:YourNamespace.Views"
xmlns:ViewModels="clr-namespace:YourNamespace.ViewModels"
...
<DataTemplate DataType="{x:Type ViewModels:MovieViewModel}">
<Views:MovieView/>
</DataTemplate>
Ok great!, now to get the Master View to actually display the current page's view, you simply need to create a ContentPresenter, and bind it's Content to the CurrentPage. Your Master View will look something like this:
<Window
...
xmlns:ViewModels="clr-namespace:YourNamespace.ViewModels">
<Window.DataContext>
<ViewModels:MasterViewModel/>
</Window.DataContext>
<Grid>
<ContentPresenter Content="{Binding CurrentPage}"/>
</Grid>
To extend this further, it's not only the MasterView that needs to contain a ContentPresenter for it's child, it is also the MovieView which needs one for it's child PickGenreViewModel. You can use the same method again:
<Grid>
<!-- The main view code for the movie view -->
...
<Border Visibility="{Binding ChildViewModel.IsDisplayed, Converter=...">
<ContentPresenter Content="{Binding ChildViewModel}"/>
</Border>
</Grid>
Note: Use a boolean to Visibility converter to determine whether to display the child content.
Using this method you don't have to worry about instantiating any views, as the DataTemplate and ContentPresenter handles that for you, all you need to worry about is mapping the view models to the appropriate view.
Phew! That was a lot to take in.
The main points to take away from this are:
You shouldn't be creating views in your view models, remember, UI is UI, Data is Data.
View model responsibilities lie with whoever owns them, for a parent-child relationship, it makes sense to let the parent manage the child, as opposed to a view model manager.
A final note is that there are certainly more than one other ways of achieving this, as I just mentioned, some kind of view and view model manager to be responsible for creating/removing views and view models.

How to bind view model to a UserControl in MVVMCROSS?

I am using the excellent Mvvmcross and Ninja Coder for Mvvmcross for building a cross platform app. For my windows store app I have created a view and a view model using Ninja coder. I have also created a UserControl which will be referenced in the view. Hence I need to bind the same viewmodel to the User control also. I have been trying to set the Data context of the user control to the singleton instance of viewmodel. I have set the data context of the user control like below.
public sealed partial class SearchResultsGridViewControl : UserControl
{
private SearchresultsViewModel _viewModel;
public SearchResultsGridViewControl()
{
this.InitializeComponent();
_viewModel = Mvx.IocConstruct<SearchresultsViewModel>();
this.DataContext = _viewModel;
}
}
But when I refer this User Control in my main view, it throws an error in XAML saying "Object Reference not set to an instance of an object. Cannot create an instance of SearchResultsGridViewControl".
This is my viewmodel:
public class SearchresultsViewModel : BaseViewModel
{
private ISearchResultsService _searchResultsService;
public SearchresultsViewModel(ISearchResultsService searchResultsService)
{
_searchResultsService = searchResultsService;
var items = _searchResultsService.DisplaySearchResults();
SchoolDetails = new ObservableCollection<School>(items);
}
private ObservableCollection<School> _schoolDetails;
public ObservableCollection<School> SchoolDetails
{
get { return _schoolDetails; }
set
{
_schoolDetails = value;
RaisePropertyChanged(() => SchoolDetails);
}
}
public ICommand RefineCommand
{
get
{
refineCommand = refineCommand ?? new MvxCommand(FilterSearchResultsBasedOnRefine);
return refineCommand;
}
}
public void FilterSearchResultsBasedOnRefine()
{
SchoolDetails = new ObservableCollection<School>(_searchResultsService.FilterSchoolsBasedOnRefine(MidDayMeals, PlayGround, DigitalClassroom, DayBoarding, TransportationFacility));
}
}
The grid view in my usercontrol is getting populated when it loads for the first time. But when RefineCommand is called to update the collection from the main view, the grid view in usercontrol is not getting updated. And I am guessing its because of that error earlier in setting the data context of the user control to view model. Please let me know what could be going wrong. I have been banging my head about it for days.
I've been using MVVMCross with Windows Store fairly recently. Without looking back at my code, I'm pretty sure that the Datacontext will inherit from it's parent unless overridden.
So as long as the MvxPage that you have presented has a viewmodel, any user control that you add to it, either in XAML or in code-behind, should share the same data context. If you are looking at doing some MVVMCross data-binding from the User Control, you should probably make sure your User Control implements IMvxStoreView, and ensure that the ViewModel property is set to the value of DataContext.
Hope that help.
Cheers,
Tristan
I think your first problem "Object Reference not set to an instance of an object" is a design time only issue - because you are trying to set the viewmodel using Mvx. at design time. You can workaround this issue if you want to by using design time viewmodels and possibly also by using one of the design time helpers (see https://github.com/MvvmCross/MvvmCross/blob/v3.1/CrossCore/Cirrious.CrossCore.Wpf/Platform/MvxDesignTimeHelper.cs).
I've no idea what your second problem is "The grid view in my usercontrol is getting populated when it loads for the first time. But when RefineCommand is called to update the collection from the main view, the grid view in usercontrol is not getting updated" - this sounds like an issue either in your xaml or in the results returned from FilterSearchResultsBasedOnRefine. From the current level of detail, I can't see what it is. My "gut feeling" is that the problem won't be MvvmCross specific - it'll just be a general Mvvm/data-binding issue.

MvvmCross navigation on screen

Our designer created a layout something like the screen above. The main idea was to create an application with only one screen, just the red part of the screen is changing (i.e. 2 textbox instead of 1 textbox) when you tap on a button. This application will be a multiplatform application and I'm using MvvmCross to create it. My question is that how can i achieve this behavior in Mvvm? My first thought was sg. like the code below, but I'm not satisfied with this solution. Do you have any better solution to this problem? Should i somehow overwrite default navigation on ShowViewModel()?
public class MainViewModel : MvxViewModel
{
private MvxViewModel _currentViewModel;
public MvxViewModel CurrentViewModel
{
get { return _currentViewModel; }
set { _currentViewModel = value; RaisePropertyChanged(() => CurrentViewModel); }
}
public MainViewModel()
{
CurrentViewModel = new DefaultViewModel();
}
public void OnButtonClick()
{
CurrentViewModel = new SecondViewModel();
}
}
public partial class MainViewModel : MvxViewController
{
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
FirstViewModel.WeakSubscribe(ViewModelPropertyChanged);
}
private void ViewModelPropertyChanged(object sender, PropertyChangedEventArgs args)
{
if (args.PropertyName == "CurrentViewModel")
{
if (Model.CurrentViewModel != null)
{
if (Model.CurrentViewModel is SecondViewModel)
{
//remove bindings
//change View
//bind new viewmodel
}
}
}
}
The alternatives for this kind of 'non-page navigation' are similar to those in MvvmCross Dialog:
You can:
Customize the MvxPresenter to allow ShowViewModel to be used
Put a special interface in the Core project and use Inversion of Control to inject the implementation from the UI project to the Core project
Use the MvxMessenger plugin and share messages between the Core and UI project which trigger this type of navigation.
Use a property with a special interface (like IInteractionRequest) on the ViewModel - that property will fire an event when the UI needs to change.
Personally, for your situation, I quite like the first of these options - intercepting ShowViewModel using a presenter.
One other alternative which I might consider is to use some kind of 'Adapter-driven' control which could very easily update it's child contents based on the CurrentViewModel property. On Android, this would be as easy as using an MvxLinearLayout with an adapter. On iOS, however, I think you'd have to write something new to do this - just because iOS doesn't really have a LinearLayout/StackPanel control.

In Prism (CAL), how can I RegisterPresenterWithRegion instead of RegisterViewWithRegion

I have a module in a Prism application and in its initialize method I want to register a presenter instead of a view with a region, i.e. I want to do this:
PSEUDO-CODE:
regionManager.RegisterPresenterWithRegion(
"MainRegion", typeof(Presenters.EditCustomerPresenter));
instead of loading a view like this:
regionManager.RegisterViewWithRegion(
"MainRegion", typeof(Views.EditCustomerView));
The presenter would of course bring along its own view and ultimately register this view in the region, but it would allow me to bind the presenter to the view in the presenter's constructor instead of binding the two together in XAML (which is more of a decoupled MVVM pattern which I want to avoid here).
How can I add a Presenter to a Region instead of a view?
namespace Client.Modules.CustomerModule
{
[Module(ModuleName = "CustomerModule")]
public class CustomerModule : IModule
{
private readonly IRegionManager regionManager;
public CustomerModule(IRegionManager regionManager)
{
this.regionManager = regionManager;
}
public void Initialize()
{
regionManager.RegisterViewWithRegion("MainRegion", typeof(Views.EditCustomerView));
}
}
}
I think your presenters should be responsible for inserting them into the region when they are activated. I usually create an IViewRegistry for my presenters to use that avoids them knowing about region names and have their presenters use this to show the view.
public class MyViewPresenter : IPresenter
{
IViewRegistry _viewReg;
IUnityContainer _container;
public MyViewPresenter(IViewRegistry viewRegistry, IUnityContainer container)
{
_viewReg = viewRegistry;
_container = container;
}
void IPresenter.Present()
{
MyView view = _container.Resolve<MyView>();
MyViewViewModel vm = _container.Resolve<MyViewViewModel>();
view.DataContext = vm;
_viewReg.ShowInMainRegion(view);
}
}
And then of course, the implementation of ShowInMainRegion would be that region registry code you already have.
public void ShowInMainRegion(object view)
{
regionManager.RegisterViewWithRegion(
"MainRegion", view);
}
There is a possibility you could do something that is more like what you want (a region adapter that detects an IViewFactory, maybe), but it's probably not practical.
Hope this helps,
Anderson
I'm still quite new to Prism but as I understand it, that doesn't make sense: Regions are designed to hold Views, aren't they. That's all they exist for. What are you hoping to get from your Region that your Presenter can use?
Given that your Presenter knows all about your View, can you use your Presenter in your RegisterViewWithRegion call:
regionManager.RegisterViewWithRegion(
"MainRegion", typeof(Presenters.EditCustomerPresenter.View));
You can try using the RegisterViewWithRegion overload that takes a delegate instead of a view type.
For example:
regionManager.RegisterViewWithRegion(RegionNames.APPLICATION_MANAGEMENT_REGION, OnGetManagementView);
public object OnGetManagementView()
{
return m_managementViewModel.View;
}
This will allow you to have your own custom logic for creating the view/viewmodel(aka presenter). The callback will be called when the named region is found.
My approach to this is to register the view with the region by passing it the View property of a resolved presenter
this.regionManager.RegisterViewWithRegion(
FoundationToolkitRegionNames.RIBBON_REGION,
() => this.container.Resolve<SetupRibbonTabPresenter>().View);
My presenters constructor would look like this:
public SetupRibbonTabPresenter(ISetupRibbonTabView view)
{
this.view = view;
}
Both the view and presenter have previously been registered in the container.

How to handle property sheet from customized editor in eclipse plugin development?

I have to bind my editor widget objects in property sheet.So that i can the property of my widget from property view.
Please help me on this, if possible provide me some code snippets.
You have a good example in the Getting started with Properties
Using the Properties view is simple enough.
Since it shows properties for the selected object, the first step to using it is to make sure that the workbench selection service knows about the object selected in your view. There’s an entire Eclipse Corner article written on the subject of the selection service
public void createPartControl(Composite parent) {
viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
viewer.setContentProvider(new ViewContentProvider());
viewer.setLabelProvider(new ViewLabelProvider());
getSite().setSelectionProvider(viewer);
viewer.setInput(getViewSite());
}
Once you have your view contributing to the workbench selection, you need to make sure that the objects that your view is selecting contribute properties
(extract)
public class Person implements IPropertySource {
private String name;
private Object street;
private Object city;
public Person(String name) {
this.name = name;
this.street = "";
this.city = "";
}
public Object getEditableValue() {
return this;
}
public IPropertyDescriptor[] getPropertyDescriptors() {
return new IPropertyDescriptor[] {
new TextPropertyDescriptor("name", "Name"),
new TextPropertyDescriptor("street", "Street"),
new TextPropertyDescriptor("city", "City")
};
}
I indicated earlier that this solution is “not necessarily [the] most correct”. This is because, for this to work, my domain object needs to know about the very view-centric (and Eclipse-centric) notion of being a property source; in short, there is a tight-coupling between the model and view and this not a good thing™.
Using adapter is a better approach, as described in this article:
Person should implement IAdaptable.
See also this recent article on how to create a custom property view
how to hack the Properties View to listen only to a specific view.
The isImportant() method is the one which decides whether to create an IPage for the specific IWorkbenchPart or not.
The idea is to override that method and return false for all the workbenchPart that we are not interested in. Lets create the view first:
<view
class="com.eclipse_tips.views.CustomPropertiesView"
icon="icons/sample.gif"
id="com.eclipse-tips.views.customePropertiesView"
name="My Properties View">
</view>
The CustomPropertiesView should extend PropertySheet and override the isImportant():
public class CustomPropertiesView extends PropertySheet {
#Override
protected boolean isImportant(IWorkbenchPart part) {
if (part.getSite().getId().equals(IPageLayout.ID_PROJECT_EXPLORER))
return true;
return false;
}
}
In this case, I'm making the view only to respond to Project Explorer and ignore other views
According to this thread, the same principle should be valid for an Editor instead of a View.
The property sheet listens to the workbench page selection provider.
The selection provider depends on what viewer/editor is active.
Each editor/viewer provides their own selection provider to use when that editor/viewer is active.
This way the property sheet doesn't care who is active, it just listens to the selection provider.
That way depending upon the view, a different set of properties are displayed.
For example, the Navigator view provides IResource selections, so the property sheet then displays IResource properties when the Navigator is active.
The Workbench Selection mechanism is illustrated in this article
The ISelectionListener is a simple interface with just one method.
A typical implementation looks like this:
private ISelectionListener mylistener = new ISelectionListener() {
public void selectionChanged(IWorkbenchPart sourcepart, ISelection selection) {
if (sourcepart != MyView.this && // 1
selection instanceof IStructuredSelection) { // 2
doSomething(((IStructuredSelection) selection).toList()); // 3
}
}
};
Depending on your requirements your listener implementation probably needs to deal with the following issues as shown in the code snippet above:
In case we also provide selections (e.g. a view or editor) we should exclude our own selection events from processing. This avoids unexpected results when the user selects elements within our part (1).
Check whether we can handle this kind of selection (2).
Get the selected content from the selection and process it (3).