如何将XAML或其他ContentView作为子元素传入ContentView?
实现MAUI自定义ContentView接受单个子元素
要实现像Frame一样可以传入单个子元素的自定义ContentView,只需按以下步骤操作:
1. 在后台代码定义可绑定的Content属性
打开EurynoteHeader.xaml.cs,添加自定义的Content可绑定属性(覆盖默认ContentView的Content属性):
namespace Eurynote.Core.Views.Common; public partial class EurynoteHeader : ContentView { public static readonly BindableProperty ContentProperty = BindableProperty.Create(nameof(Content), typeof(View), typeof(EurynoteHeader), null); public new View Content { get => (View)GetValue(ContentProperty); set => SetValue(ContentProperty, value); } public EurynoteHeader() { InitializeComponent(); } }
2. 在XAML中添加内容呈现容器
回到Header.xaml,在需要显示动态内容的位置添加ContentPresenter,并绑定到刚才定义的Content属性:
<?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" xmlns:common="clr-namespace:Eurynote.Core.Views.Common" x:Class="Eurynote.Core.Views.Common.EurynoteHeader"> <HorizontalStackLayout Spacing="10" VerticalOptions="Center"> <Image Source="brand_icon" WidthRequest="32" HeightRequest="30" /> <Label Text="Header" Margin="0,-3,0,0" /> <!-- 动态内容呈现位置 --> <ContentPresenter Content="{Binding Content, Source={RelativeSource AncestorType={x:Type common:EurynoteHeader}}}" /> </HorizontalStackLayout> </ContentView>
3. 使用自定义视图
现在你可以像使用Frame一样,在调用时传入单个子元素:
<common:EurynoteHeader> <Button Text="Button" /> </common:EurynoteHeader> <common:EurynoteHeader> <common:AnotherView /> </common:EurynoteHeader>
这样就能确保每次只能传入一个View类型的内容,和Frame的行为完全一致。
内容的提问来源于stack exchange,提问作者Ajay Verma
相关产品推荐
相关产品推荐

