我的 Xamarin 项目中有多个 ContentPage xaml 文件。我想在每个 ContentPage 中嵌入一段共享的 xaml。xaml 的共享部分没有什么特别之处(它不需要做任何特定于平台的事情)。难道不应该像在 ContentPage 的 xaml 中嵌入标签以包含共享的 xaml 文件一样简单吗?有人可以指出我正确的方向吗?
2 回答
非常感谢 IdoT,它确实对我有用,但是在添加了一些行之后。因为这将有助于制作模板/自定义控件/子表单,以便在 Xamarin.Forms 中轻松添加/共享。
这是我根据您的建议完成的全部工作,因此可以与其他人一起使用:
HeaderNavigationBar.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="App9.MVC.Views.HeaderNavigationBar"
Orientation="Horizontal"
HorizontalOptions="FillAndExpand"
Padding="10"
ackgroundColor="White">
<Button Text="Internal 1" />
<Button Text="Internal 2" />
</StackLayout>
如您所见,添加了:
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
在 中HeaderNavigationBar.cs
,它被声明为StackLayout
:
HeaderNavigationBar.cs
using Xamarin.Forms;
namespace App9.MVC.Views
{
public partial class HeaderNavigationBar : StackLayout
{
public HeaderNavigationBar()
{
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:App9.MVC.Views;assembly=App9"
x:Class="App9.MVC.Views.MainView">
<StackLayout Padding="0,0,0,20">
<common:HeaderNavigationBar>
<Button Text="External 1" />
</common:HeaderNavigationBar>
<Button Text="Test Button 1
x:Name="btnPage1"
Clicked="btnPage1_clicked" />
</StackLayout>
</ContentPage>
如您所见,命名空间具有完整路径,位于MainView
:
xmlns:common="clr-namespace:App9.MVC.Views;assembly=App9"
此外,您会注意到有一个名为 的按钮External 1
,它也会与内部按钮一起显示,因为该控件是 StackLayout,因此它可以处理添加更多控件。
截屏:
也适用于另一个页面内的页面:
- https://github.com/twintechs/TwinTechsFormsLib
- http://blog.twintechs.com/advanced-xamarin-forms-techniques-for-flexible-and-performant-cross-platform-apps-part-5-page-in-page-embedding
再次感谢 IdoT。
您可以获取您的父子项ContentPage
(例如,包装所有子项的StackLayout),将其放入外部 xaml 文件中,然后将该组件包含在每个 ContentPages 中。
外部 xaml 文件将是StackLayout类型,而不是 ContentPage。
编辑- 添加了一个代码示例:
让我们添加一个标题 StackLayout:我们在类后面添加一个代码:
public partial class HeaderNavigationBar
{
public HeaderNavigationBar()
{
InitializeComponent();
}
}
然后添加 XAML 代码:
<StackLayout x:Class="HeaderNavigationBar"
Orientation="Horizontal"
HorizontalOptions="FillAndExpand"
Padding="10"
BackgroundColor="White">
<Image Source="burger_icon"
HorizontalOptions="StartAndExpand"
Aspect="AspectFit">
<Image.GestureRecognizers>
<TapGestureRecognizer Command="{Binding SlideNavigationDrawerCommand}" />
</Image.GestureRecognizers>
</Image>
</StackLayout>
最后,在您要重用组件的页面中 - 添加此引用:<HeaderNavigationBar />
.