我正在尝试在我的 xamarin 应用程序中定义可重用组件。我的意图是在多个文件中使用相同的 xaml。例如,我需要为我的应用程序定义公共标头。我尝试通过以下方式实现这一点:在单独的文件中定义所需的 xaml。使用关联的类名以在任何其他 xaml 中重用。
可重复使用的 xaml :
<?xml version="1.0" encoding="utf-8" ?>
<StackLayout xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="AppHeader" BackgroundColor="White"
Spacing="1"
VerticalOptions="Start">
<StackLayout Padding="0,10,0,10"
BackgroundColor="Blue"
Orientation="Horizontal"
Spacing="0">
<Label
Text="AppName"
HorizontalTextAlignment="Center"
HorizontalOptions="Center"
TextColor="White"
></Label>
</StackLayout>
</StackLayout>
相关类:
public partial class AppHeader : StackLayout
{
public AppHeader ()
{
InitializeComponent();
}
}
xaml 中的用法
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:common="clr-namespace:MyApp;assembly=MyApp"
x:Class="MyApp.SampleView">
<StackLayout>
<common:AppHeader></common:AppHeader>
</StackLayout>
</ContentPage>
运行应用程序时,我收到可重用 xaml 文件的以下错误:
“当前上下文中不存在名称‘InitializeComponent’”
实现看起来很简单,但我无法确定缺少什么。有什么解决办法吗?任何帮助将非常感激。谢谢