ContentView是一個允許創建自定義、可重用控件的控件(controls),並且只能包含單一child。並且衍生自TemplatedView類,該類定義ControlTemplate bindable property,其定義控制項的外觀
我們創立一個新的資料夾Views來放置我們自定義的控件
並創建新項目命名為CardView
打開能看到CardView繼承於ContentView
Todo\Views\CardView.xaml.cs
namespace Todo.Views;
public partial class CardView : ContentView
{
public CardView()
{
InitializeComponent();
}
}
Todo\Views\CardView.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Todo.Views.CardView">
<VerticalStackLayout>
<Label
Text="Welcome to .NET MAUI!"
VerticalOptions="Center"
HorizontalOptions="Center" />
</VerticalStackLayout>
</ContentView>
自定義
接下來我們開始自定義,首先我們先自定義卡片名稱屬性
CardView.xaml.cs
namespace Todo.Views;
public partial class CardView : ContentView
{
public static readonly BindableProperty CardTitleProperty = BindableProperty.Create(nameof(CardTitle), typeof(string), typeof(CardView), string.Empty);
public string CardTitle
{
get => (string)GetValue(CardView.CardTitleProperty);
set => SetValue(CardView.CardTitleProperty, value);
}
public CardView()
{
InitializeComponent();
}
}
使用可系結屬性(BindableProperty)來定義出我們的CardTitleProperty
可系結屬性的功能:
- 做為資料系結的valid target property
- 透過樣式設定property
- 提供與property類型之預設值不同的預設property值
- 驗證property的值
- 監視property變更
CardView.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Name="this"
x:Class="Todo.Views.CardView">
<Frame BindingContext="{x:Reference this}" Margin="15">
<Grid>
<Label Text="{Binding CardTitle, FallbackValue='This is Card Title'}" />
</Grid>
</Frame>
</ContentView>
ContentViewx:Name屬性設定為 this ,可用來存取系結至CardView實例的物件
接著我們來使用我們自定義的控件
打開我們的Todo\Pages\UserPage.xaml
加入CardView
加入自訂控制項命名空間的參考並使用xmlns:controls="clr-namespace:Todo.Views"
<controls:CardView />
UserPage.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:Todo.Views"
x:Class="Todo.UserPage"
Title="UserPage">
<FlexLayout Direction="Column"
AlignItems="Center"
JustifyContent="SpaceEvenly">
<controls:CardView CardTitle="Hi"/>
<controls:CardView CardTitle='Test' />
</FlexLayout>
</ContentPage>
接著回到我們的App