Bing在universal app中映射MVVM
很长一段时间以来,我一直在试图理解在n MVVM场景中处理bing地图的正确方法 我可能会在我的XAML视图中创建一个映射,如下所示:Bing在universal app中映射MVVM,mvvm,bing-maps,Mvvm,Bing Maps,很长一段时间以来,我一直在试图理解在n MVVM场景中处理bing地图的正确方法 我可能会在我的XAML视图中创建一个映射,如下所示: <map:Map x:Name="MyMap" Credentials="MySuperSecretCredentials"/> private async void FindMe_Clicked() { _cts = new CancellationTokenSource(
<map:Map x:Name="MyMap"
Credentials="MySuperSecretCredentials"/>
private async void FindMe_Clicked()
{
_cts = new CancellationTokenSource();
CancellationToken token = _cts.Token;
// Get the location.
Geoposition pos = await _geolocator.GetGeopositionAsync().AsTask(token);
MyMap.SetView(new BasicGeoposition() { Latitude = pos.Coordinate.Latitude, Longitude = pos.Coordinate.Longitude }, 15);
}
public class MainViewModel
{
public RelayCommand GetLocation { get; private set; }
public MainViewModel()
{
this.GetLocation = new RelayCommand(this.FindMe());
}
public void FindMe()
{
_cts = new CancellationTokenSource();
CancellationToken token = _cts.Token;
// Get the location.
Geoposition pos = await _geolocator.GetGeopositionAsync().AsTask(token);
MyMap.SetView(new BasicGeoposition() { Latitude = pos.Coordinate.Latitude, Longitude = pos.Coordinate.Longitude }, 15);
}
}
只需引用MyMap,我们就可以在代码隐藏中随心所欲地使用它。
但是如何在viewModel中执行相同的命令
我想我应该先用调用viewModel上的方法的命令替换单击的FindMe
?并让该方法执行与代码隐藏中的方法类似的方法。但是如何访问viewModel中的MyMap
也许我的虚拟机是这样的:
<map:Map x:Name="MyMap"
Credentials="MySuperSecretCredentials"/>
private async void FindMe_Clicked()
{
_cts = new CancellationTokenSource();
CancellationToken token = _cts.Token;
// Get the location.
Geoposition pos = await _geolocator.GetGeopositionAsync().AsTask(token);
MyMap.SetView(new BasicGeoposition() { Latitude = pos.Coordinate.Latitude, Longitude = pos.Coordinate.Longitude }, 15);
}
public class MainViewModel
{
public RelayCommand GetLocation { get; private set; }
public MainViewModel()
{
this.GetLocation = new RelayCommand(this.FindMe());
}
public void FindMe()
{
_cts = new CancellationTokenSource();
CancellationToken token = _cts.Token;
// Get the location.
Geoposition pos = await _geolocator.GetGeopositionAsync().AsTask(token);
MyMap.SetView(new BasicGeoposition() { Latitude = pos.Coordinate.Latitude, Longitude = pos.Coordinate.Longitude }, 15);
}
}
如果我没有想到这个问题,那么我需要做的就是以某种方式将视图中存在的MyMap
的相同实例传递给我的viewmodel
非常感谢您的帮助,如果有人在某处遇到过bibg映射、可移植类库或Mvvm模式,我也很乐意看到任何关于如何使用bibg映射的示例。谢谢 遵循MVVM模式时,绝对不应尝试从Viewmodel中访问视图层的元素(例如贴图控件)。相反,您(理论上)应该创建两个公共属性
CenterLatitude
和CenterLatitude
,并将它们直接绑定到XAML代码中的maps控件:
<Map Credentials="MySuperSecretCredentials" ZoomLevel="15">
<Map.Center>
<Location Latitude="{Binding CenterLatitude}" Longitude="{Binding CenterLongitude}"/>
</Map.Center>
</Map>
在Viewmodel中使用方法FindMe
是可以的,但是不要访问MyMap
控件并从其中调用SetView(…)
,您只需更新两个属性CenterLatitude
和CenterLatitude
,并确保引发PropertyChanged
事件,以便向视图通知已更改的数据并更新自身
但是:不幸的是,bing地图控件的Center
属性不支持数据绑定-似乎Microsoft出于性能原因故意关闭了此功能。如果您仍然希望保留MVVM模式,请查看解释如何绕过此限制的内容
(根据我的经验,此解决方案工作得很好,不会影响性能。请确保不要太频繁地更新Center
属性,即每秒几次…)