MVVM in WPF - UserControls and GMap.NET

戏子无情 提交于 2020-01-07 04:38:09

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/45152773/mvvm-in-wpf-usercontrols-and-gmap-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!