【问题标题】:Bing Maps MVVM in universal app通用应用程序中的 Bing Maps MVVM
【发布时间】:2014-12-23 18:23:09
【问题描述】:

很长一段时间以来,我一直试图了解在 n MVVM 场景中处理 bing Maps 的正确方法。

我可能会像这样在我的 XAML 视图中创建一个映射:

<map:Map x:Name="MyMap"
                 Credentials="MySuperSecretCredentials"/>

我可以像这样轻松地与 map for eaxmple 交互文件背后的代码:

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);

        }

只需引用 MyMap,我们就可以在后面的代码中使用它做任何我们喜欢的事情。 但是我怎样才能在我的 viewModel 中执行相同的命令呢?

我想我应该先用调用我的 viewModel 上的方法的命令替换 FindMe_Clicked?并让该方法执行类似于代码隐藏中的方法。但是如何在 viewModel 中访问MyMap

也许我的虚拟机看起来像这样:

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 的相同实例传递给我的视图模型?

非常感谢您的帮助,如果有人在某个地方遇到过,我也很想看到如何使用 bibg 映射、可移植类库或 Mvvm 模式的任何示例。谢谢!

【问题讨论】:

    标签: mvvm bing-maps


    【解决方案1】:

    当遵循 MVVM 模式时,您不应该尝试从 Viewmodel 中访问 View 层的元素(例如地图控件)。相反,您将(理论上)创建两个公共属性 CenterLatitudeCenterLongitude 并将它们直接绑定到 XAML 代码中的地图控件:

    <Map Credentials="MySuperSecretCredentials" ZoomLevel="15">
        <Map.Center>
            <Location Latitude="{Binding CenterLatitude}" Longitude="{Binding CenterLongitude}"/>
        </Map.Center>
    </Map>
    

    在 Viewmodel 中有一个方法 FindMe 是可以的,但不是访问 MyMapcontrol 并从那里调用 SetView(...),您只需更新两个属性 CenterLatitudeCenterLongitude 和确保引发 PropertyChanged 事件,以便通知 View 更改的数据并自行更新。

    但是:不幸的是,必应地图控件的Center 属性不支持数据绑定——微软似乎出于性能原因有意关闭了此功能。如果您仍想保留 MVVM 模式,请查看 this article I've written some time ago,其中说明了如何规避此限制。

    (根据我的经验,这种解决方法效果很好,不会影响性能。只要确保您不要过于频繁地更新 Center 属性,这意味着每秒几次...)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多