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

MAUI自定义控件XAML无法使用标准控件及Grid.Row属性问题

MAUI自定义控件XAML命名空间错误解决方案

问题场景

在MAUI项目中创建自定义控件时,参考Xamarin.Forms示例代码编写XAML后遇到两个连续错误:

  1. 初始代码报错:未找到类型‘Grid’。请确认未缺失程序集引用且所有引用程序集已生成。
  2. 按提示添加xmlns:maui="http://schemas.microsoft.com/dotnet/2021/maui/design"命名空间后,新报错:未在类型‘Grid’中找到可附加属性‘Row’。

原参考的XAML代码:

<?xml version="1.0" encoding="utf-8" ?>
<Grid xmlns="http://xamarin.com/schemas/2014/forms"
                xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                x:Class="MyProject.Controls.MyActivityIndicator"
                xmlns:local="clr-namespace:MyProject"
                HorizontalOptions="FillAndExpand" 
                x:Name="this">

    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Label x:Name="LoadingLabel" FontAttributes="Bold" Grid.Row="0" HorizontalOptions="CenterAndExpand" />
    <ActivityIndicator x:Name="ActivityIndicator" Grid.Row="1" HorizontalOptions="CenterAndExpand" />
</Grid>

问题原因

MAUI与Xamarin.Forms的XAML核心命名空间不兼容:

  • 原代码使用Xamarin.Forms的命名空间http://xamarin.com/schemas/2014/forms,MAUI项目无法识别该命名空间下的控件。
  • 后续添加的maui命名空间是设计时专用命名空间,仅用于预览器设计元素,不包含运行时控件的完整属性(如Grid.Row附加属性)。

解决方法

将XAML根元素的核心命名空间替换为MAUI官方运行时命名空间,移除多余的设计时命名空间:

修改后的完整XAML代码:

<?xml version="1.0" encoding="utf-8" ?>
<Grid xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
      xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
      x:Class="MyProject.Controls.MyActivityIndicator"
      xmlns:local="clr-namespace:MyProject"
      HorizontalOptions="FillAndExpand" 
      x:Name="this">

    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Label x:Name="LoadingLabel" FontAttributes="Bold" Grid.Row="0" HorizontalOptions="CenterAndExpand" />
    <ActivityIndicator x:Name="ActivityIndicator" Grid.Row="1" HorizontalOptions="CenterAndExpand" />
</Grid>

关键修改点

  • 替换核心命名空间:将xmlns="http://xamarin.com/schemas/2014/forms"改为xmlns="http://schemas.microsoft.com/dotnet/2021/maui",这是MAUI所有基础控件的官方命名空间。
  • 删除冗余命名空间:移除xmlns:maui="http://schemas.microsoft.com/dotnet/2021/maui/design",避免混淆运行时控件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 05:44:59