PamanBeruang
PamanBeruang

Reputation: 1589

accessing xaml control from mainviewmodel

I have maps control in my xaml windows phone apps and I want to access my map from my mainviewmodel since there is where I put all my logic code in there, is there anyway to add it?

Geoposition position = await 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();

this is the code that supposed to be in there if i just put all my code into mainpage.xaml.cs

myMap.SetView(gpsCenter, 10);

this is the code that i trying to add into my xaml component, it only doing some zoom and moving my map to exactly the phone position data, i can put it into mainpage.xaml.cs but since there is 2 variable that i needed in my mainviewmodel (latitude and longitude) so i decided to put it all into mainviewmodel

edit

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

Upvotes: 0

Views: 145

Answers (1)

Toni Petrina
Toni Petrina

Reputation: 7122

You shouldn't do that. Your view model should never interact with the view directly. You should create a bindable GeoCoordinate property in your view model and bind that to the Map.Center property.

This way you still have clean separation of UI and view model code.

-- EDIT: Add the following property to your view model

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

Bind Map.Center to that property in XAML.

Upvotes: 1

Related Questions