.netwpfmodel-view-controllermvvmgmap.net

MVVM in WPF - UserControls and GMap.NET


I have read almost all the tutorials and checked stack questions however I still do not know and do not understand how to manage WPF UserControls in MVVM, specially those provided by others like GMap.NET.

I am trying to follow MVVM pattern in my app, however I have no idea how to initialize and manage GMap.NET WPF control in it. In standard approach it requires management like this:

gmap.MapProvider = GMap.NET.MapProviders.GoogleMapProvider.Instance;
GMap.NET.GMaps.Instance.Mode = GMap.NET.AccessMode.ServerOnly;
gmap.DragButton = MouseButton.Left;
gmap.SetPositionByKeywords("Paris, France");
gmap.ShowCenter = false;

How can I do this without braking MVVM? Is it possible? I would be grateful for any help.


Solution

  • As suggested in comments, any code that just initializes the view can be placed in code behind.

    If possible, properties from the view model should be bound the view. That is the prefered way and should beat down the most use cases.

    However, some controls are complex and have an "advanced" API that consists not only of dependency properties, but also of methods and event.

    If it is required to call "view methods" from the view model, the event-based approch works fine. Becuase the view knowns the view model, it can subscribe to events on the view model (e.g. in the DataContextChanged event). (see also that answer) Example: You want to call the method gmap.SetPositionByKeywords from the view model. Just give the view model an event RequestSetPositionByKeyWords, let the view subscibe to that method and call gmap.SetPositionByKeywords if the event has been raised. Parameters and return values can be transfered by event args. That is a nice approch which respects the MVVM principals.