好吧,如果你想创建一个可重用的ContentView
.NET MAUI,您可以创建Control Templates
with Content Presenter
进而reuse它在您想要的页面中。
您可以参考下面的详细步骤来了解如何使用它。
1.创建自定义控件:自定义控件.xaml继承自ContentView
with a custom
BindableProperty 如下所示:
XAML:
<ContentView.ControlTemplate>
<ControlTemplate>
<Frame>
<VerticalStackLayout>
<Label Text="{TemplateBinding Title}"/>
<ContentPresenter/>
</VerticalStackLayout>
</Frame>
</ControlTemplate>
</ContentView.ControlTemplate>
隐藏代码:
public partial class CustomControl : ContentView
{
public static readonly BindableProperty TitleProperty =
BindableProperty.Create(nameof(Title), typeof(string), typeof(CustomControl) );
public CustomControl()
{
InitializeComponent();
}
public string Title
{
get => GetValue(TitleProperty) as string;
set => SetValue(TitleProperty, value);
}
}
2.您可以在以下位置多次重复使用它MainPage.xaml
像下面这样:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:controls="clr-namespace:MauiAppCustomDemo.Controls"
x:Class="MauiAppCustomDemo.MainPage">
<ScrollView>
<VerticalStackLayout
Spacing="25"
Padding="30,0"
VerticalOptions="Center">
<controls:CustomControl Title="Hello World">
<VerticalStackLayout>
<Label Text="Label 1"/>
<Label Text="Label 2"/>
</VerticalStackLayout>
</controls:CustomControl>
<controls:CustomControl Title="Hello again">
<HorizontalStackLayout>
<Label Text="Label 3"/>
<Label Text="Label 4"/>
</HorizontalStackLayout>
</controls:CustomControl>
</VerticalStackLayout>
</ScrollView>
</ContentPage>
微软官方参考链接:https://learn.microsoft.com/en-us/dotnet/maui/fundamentals/controltemplate?view=net-maui-7.0 https://learn.microsoft.com/en-us/dotnet/maui/fundamentals/controltemplate?view=net-maui-7.0