1

我正在尝试在我的 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’”

实现看起来很简单,但我无法确定缺少什么。有什么解决办法吗?任何帮助将非常感激。谢谢

4

2 回答 2

2

在您StackLayout的课程中,您有一个属性:x:Class="AppHeader". 这应该指定完全限定的类名,包括命名空间。所以编辑它是这样的:

<StackLayout xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="YouNameSpace.AppHeader" BackgroundColor="White"
             Spacing="1"
             VerticalOptions="Start">
  <StackLayout Padding="0,10,0,10" ...
于 2016-09-30T11:36:17.403 回答
0

InitializeComponent();从您的AppHeader构造函数中删除。InitializeComponent()仅由ContentPages 使用。

此外,刚刚注意到您在AppHeaderXAML 中的 XML。将 XAML 更改为此(删除仅在 a 中需要的所有样板 XAML ContentPage

<StackLayout 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>
于 2016-09-30T01:37:32.173 回答