我的 Xamarin 项目中有多个 ContentPage xaml 文件。我想将一个共享的 xaml 嵌入到每个 ContentPage 中。共享的 xaml 部分没有什么特别之处(它不需要做任何特定于平台的事情)。难道不应该像在 ContentPage 的 xaml 中嵌入标记以包含共享的 xaml 文件一样简单吗?有人可以指出我正确的方向吗?
最佳答案
非常感谢 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();
}
}
}
然后对于将容纳它/显示它的页面:
MainView.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,所以它可以处理添加更多控件。
截图:
同样对于另一个页面内的页面:
再次感谢 IdoT。
关于Xamarin.Forms:我可以将一个 ContentPage 或 ContentView 嵌入到另一个 ContentPage 中吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30417671/