Xaml部分声明类不一致报错:ContentPage与ContentView基类不匹配求助
解决「Xaml Partial Declarations must not specify different classes」错误
这个错误的核心原因是XAML文件与C#代码中定义的类基类不匹配:
- XAML的根节点是
<ContentView>,编译器会自动生成继承自ContentView的部分类 - 你的C#代码里却让
CellularFrequencies继承自ContentPage,两者基类冲突,触发了编译器报错
两种修复方案:
方案1:保持C#代码的ContentPage基类,修改XAML根节点
将XAML的根节点从<ContentView>改为<ContentPage>:
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:CellularSignal1" x:Class="CellularSignal1.CellularFrequencies"> <ScrollView> <StackLayout> </StackLayout> </ScrollView> </ContentPage>
方案2:保持XAML的ContentView根节点,修改C#代码基类
将C#代码中的基类从ContentPage改为ContentView:
#if ANDROID namespace CellularSignal1; using Microsoft.Maui.Controls; public partial class CellularFrequencies : ContentView { public CellularFrequencies() { InitializeComponent(); BindingContext = this; } } #endif
你修改XAML类名后能正常运行,是因为新类名对应的自动生成代码,和你写的C#代码基类达成了一致,本质还是解决了基类不匹配的问题。
内容的提问来源于stack exchange,提问作者rickster26ter1
相关产品推荐
相关产品推荐

