2014-01-14 41 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任何想法爲什麼? –