Display Map in winui3 with Mapsui and a separated ViewModel file

173 Views Asked by At

I am trying to display a map in Winui3 with Mapsui and a separate MVVM file. Just to getting started.

If I'm using MapControl in ViewModel file i get multiple null errors and with Map it just doesnt show up.

I just trying to follow the getting started but with a ViewModel file. With MapControl

ViewModel with MapControl(a lot of nulls errors):

public class MyMapViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private Map _map;
        public Map Map
        {
            get { return _map; }
            set
            {
                _map = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Map)));
            }
        }

        public MyMapViewModel()
        {
            Map = new Map();
            Map.Layers.Add(OpenStreetMap.CreateTileLayer());
        }
    }

ViewModel with Map

 public class MyMapViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private Map _map;
        public Map Map
        {
            get { return _map; }
            set
            {
                _map = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Map)));
            }
        }

        public MyMapViewModel()
        {
            Map = new Map();
            Map.Layers.Add(OpenStreetMap.CreateTileLayer());
        }
    }

Code-behind file

    public sealed partial class MapsuiMVVMControl : UserControl
    {
        public MapsuiMVVMControl()
        {
            this.InitializeComponent();
            this.DataContext = new MapViewModel();
        }
    }

Xaml for code-behind file

<Grid>
        <!--<Grid.DataContext>
            <vm:MyMapViewModel />
        </Grid.DataContext>-->
        <Grid.DataContext>
            <vm:MapViewModel />
        </Grid.DataContext>
        <winui:MapControl x:Name="MyMap" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" />
1

There are 1 best solutions below

0
On

Ok, using viewModels is good, but I think you did not understand the purpose of a viewmodel. The mapsui maps component is actually a control where the user can interact with. And because of being a control, it must be manipulated in the code behind file of the page => the model. So what you can do (and sure this works) :

C# '''

public sealed partial class YourPage : Page
{
   public YourPage()
   {
      this.InitializeComponent();
      MyMap.Map.Layers.Add(OpenStreetMap.CreateTileLayer());
   }
}

'''

Xaml: ''' <mapsui:MapControl x:Name="MyMap" /> '''

Link to this: https://xamlbrewer.wordpress.com/2023/07/25/displaying-maps-in-winui-3-with-open-source-libraries/ Hope this helps, otherwise let me know