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'在當前上下文中不存在」
該實現看起來很簡單,但我無法確定缺少的內容。 任何解決方案? 任何幫助將不勝感激。 謝謝
在你的'StackLayout'你必須爲你的類屬性:'X:類=「AppHeader」'如果我沒有記錯的話,你必須指定那裏的完整命名空間以及您的課程名稱 –
你是對的。提供完整的名稱空間解決了問題 – user3165999
讓我將它升級到答案,以便您可以接受它 –