2014-01-14 40 views
0

我在我的xaml windows手机应用程序中有地图控件,我想从我的mainviewmodel访问我的地图,因为有我将所有逻辑代码放在那里的地方,是否有添加它?从mainviewmodel访问xaml控件

Geoposition位置= 等待geolocator.GetGeopositionAsync( TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(30));

  var gpsCenter = 
       new GeoCoordinate(
        position.Coordinate.Latitude, 
        position.Coordinate.Longitude); 
      myMap.SetView(gpsCenter, 10); 
      latitude = position.Coordinate.Latitude; 
      longitude = position.Coordinate.Longitude; 
      UpdateTransport(); 

这是应该在那里,如果我只是把我所有的代码到MainPage.xaml.cs中

myMap.SetView(gpsCenter,10)的代码;

这是我尝试添加到我的XAML组件的代码,它只是做一些缩放和移动地图我正好手机位置数据,我可以把它变成MainPage.xaml.cs中,但因为有2变量,我需要在我的mainviewmodel(经度和纬度),所以我决定把它全部纳入mainviewmodel

编辑

private GeoCoordinate _center; 
    public GeoCoordinate center 
    { 
     get { return _center; } 
     set { this.SetProperty(ref this._center, value); } 
    } 

    public MainViewModel() 
    { 
     center = new GeoCoordinate(); 
    } 

    private async void LoadTransportData() 
    { 
     Geolocator geolocator = new Geolocator(); 
     geolocator.DesiredAccuracyInMeters = 50; 
    Geoposition position = 
        await geolocator.GetGeopositionAsync(
        TimeSpan.FromMinutes(1), 
        TimeSpan.FromSeconds(30)); 

    center = new GeoCoordinate(
          position.Coordinate.Latitude, 
          position.Coordinate.Longitude); 
    } 

回答

1

你不应该这样做。您的视图模型应该从不直接与视图交互。您应该在视图模型中创建一个可绑定的GeoCoordinate属性,并将其绑定到Map.Center属性。

这样你仍然有清晰的用户界面和视图模型代码分离。

- 编辑:下面的属性到您的视图模型

GeoCoordinate _center; 
public GeoCoordinate Center 
{ 
    get { return _center; } 
    set 
    { 
     _center = value; 
     OnPropertyChanged("Center"); // or whatever here 
    } 
} 

绑定Map.Center添加到XAML该属性。

+0

如何创建可绑定的地理坐标? –

+0

对于那看到我的编辑。 –

+0

已经做了你所做的事情,但得到System.ArgumentNullException任何想法为什么? –