2016-09-30 56 views
0

Iam嘗試在我的xamarin應用程序中定義可重用組件。我的目的是在多個文件中使用相同的xaml。例如,我需要爲我的應用程序定義通用標題。我試圖按照以下方式實現它:在單獨的文件中定義所需的xaml。使用關聯的類名稱在其他任何xaml中重用。以xamarin形式實現可重用元素

可重複使用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> 

關聯類:在XAML

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

使用

<?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'在當前上下文中不存在」

該實現看起來很簡單,但我無法確定缺少的內容。 任何解決方案? 任何幫助將不勝感激。 謝謝

+0

在你的'StackLayout'你必須爲你的類屬性:'X:類=「AppHeader」'如果我沒有記錯的話,你必須指定那裏的完整命名空間以及您的課程名稱 –

+0

你是對的。提供完整的名稱空間解決了問題 – user3165999

+0

讓我將它升級到答案,以便您可以接受它 –

回答

0

在你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" ... 
+0

不顯示常用xaml頁面的InitializeComponent()元素 – user3165999

+0

那麼會刮傷;) –

0

從您的AppHeader構造函數中刪除InitializeComponent();InitializeComponent()僅用於ContentPage s。

此外,只注意到您在AppHeader XAML中擁有的XML。該XAML更改爲這個(刪除所有樣板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> 
+0

我嘗試刪除InitializeComponent(),但不顯示常見xaml的元素 – user3165999