xamlxamarin.formsinitializecomponent

Implement Reusable elements in xamarin forms


Iam trying to define reusable components in my xamarin app. My intention is to use same xaml in multiple files. For example, I need to define common header for my app. I tried to implement this in following way : Define required xaml in separate file. Use the class name associated for reusing in any other xaml.

Reusable 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>

Associated Class :

public partial class AppHeader : StackLayout
    {
        public AppHeader ()
        {
           InitializeComponent();
        }
    }

Usage in 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>

While running the app, Im getting following error for reusable xaml file:

"The name 'InitializeComponent' does not exist in the current context"

The implementation look simple, but Im not able to identify what is missing. Any solution for this? Any help would be much appreciated. Thanks


Solution

  • In your StackLayout you have an attribute for your class: x:Class="AppHeader". This should specify the fully qualified class name including the namespace. So edit it to be something like:

    <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" ...