Binding Mapsui Map to Xaml and with MVVM and service architecture

293 Views Asked by At

Goal:

I try to display a map from Mapsui with MVVM and a service. And CommunityToolkit.Mvvm is installed and can be used for the ViewModel.

My error:

Exception thrown: 'System.InvalidCastException' in System.Private.CoreLib.dll Exception thrown: 'Microsoft.UI.Xaml.Markup.XamlParseException' in WinRT.Runtime.dll WinRT information: Failed to assign to property 'Mapsui.UI.WinUI.MapControl.Map'. [Line: 18 Position: 119] XAML parsing failed.

And its happens in the code-behind file:

    public sealed partial class MainWindow : Window
    {
        public MainWindow()
        {
            this.InitializeComponent();
        }
    }

I don’t think I created the Map for the Xaml file but how to bind it correctly? With Map="{Binding Map}" or DataContext? Or something else?

My simple github project is public.

My xaml file

    <Grid>
        <Grid.DataContext>
            <viewmodels:MapViewModel/>
        </Grid.DataContext>
        <winui:MapControl x:Name="MyMap" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Map="{Binding Map}"/>
    </Grid>

My Code-behind file

Datacontext = ViewModel or something?

    public sealed partial class MainWindow : Window
    {
        public MainWindow()
        {
            this.InitializeComponent();
        }
    }

My ViewModel code

    public partial class MapViewModel : ObservableObject
    {
        //[ObservableProperty]
        private Map _map;

        private readonly IMapService mapService;

        public MapViewModel()
        {
            mapService = new MapService();
            Map = mapService.GetMap();
        }

        public Map Map
        {
            get => _map;
            set => SetProperty(ref _map, value);
        }
    }

MapService

    public class MapService : IMapService
    {

        private Map _map;
        public MapService()
        {
            _map = new Map();
        }

        public Map GetMap()
        {
            _map.Layers.Add(OpenStreetMap.CreateTileLayer());
            return _map;
        }
    }
    public interface IMapService
    {
        Map GetMap();
    }
0

There are 0 best solutions below