You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Maui中嵌入ContentView的Mapsui MapView显示空白问题

.NET Maui中ContentView嵌入Mapsui MapView显示空白的问题解决

问题原因

问题出在MapView构造函数的执行逻辑和对象实例化冲突上:

  1. 你在构造函数中先手动new了一个MapView实例并赋值给_mapView,还为它添加了OpenStreetMap图层。
  2. 随后调用的InitializeComponent()方法会根据XAML文件重新创建所有界面元素,包括XAML里定义的x:Name="_mapView"控件,这直接覆盖了你之前手动创建的带图层的MapView实例。
  3. 最终界面渲染的是XAML初始化的全新MapView,它没有任何图层配置,因此显示空白。

解决方案

调整构造函数的执行顺序,先加载XAML控件,再对XAML中已存在的_mapView进行配置,不要手动实例化新的MapView对象。

修正后的MapView.xaml.cs

using Mapsui.UI.Maui;
using MauiApp7.Pages.ViewModels;

namespace MauiApp7.Pages;

public partial class MapView : ContentView
{
    public MapViewModel ViewModel => BindingContext as MapViewModel;

    public MapView()
    {
        BindingContext = ServiceProvider.GetService<MapViewModel>();
        // 先初始化XAML中的所有控件
        InitializeComponent();
        // 直接操作XAML里定义的_mapView实例
        _mapView.Map.Layers.Add(Mapsui.Tiling.OpenStreetMap.CreateTileLayer());
    }

    private async void GetLocationAsync(object sender, EventArgs EventArgs)
    {
        //Do something
    }
}

额外优化(可选)

XAML中的MapView同时设置了AbsoluteLayout属性和Grid.Row布局属性,二者存在冲突,建议移除AbsoluteLayout相关配置,避免布局异常:

<mapsui:MapView x:Name="_mapView"
                VerticalOptions="FillAndExpand"
                HorizontalOptions="FillAndExpand"
                BackgroundColor="Gray" 
                Grid.Row="1"/>

内容的提问来源于stack exchange,提问作者njun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 15:03:18