如何在 .NET MAUI 中创建可重用组件?

9
我最近开始使用 .Net MAUI,但现在我想知道如何在所有页面上使用一段代码,例如自制的导航栏,因为在所有 10 个页面上编写相同的代码没有意义。我想知道是否有一种像 React 或 Angular 中可以重复使用的组件创建方式?
PS:这个问题不仅限于导航栏,而是关于在 .NET MAUI 中通用代码的重复使用。
到目前为止,我已经观看了各种视频和文章,但它们更多地涉及自定义控件,并没有帮助我。大多数文章与 this 视频中所传达的内容相符。我也看到了 this 文章,但它也没有帮助我。
谢谢你的帮助 :)

定义一个自定义视图,就像您只使用它一次一样。从ContentView或任何Layout类继承。向其中添加BindableProperty;这就是为您的视图提供“参数”的方式,因此可以在每次使用时进行自定义重用。现在,您可以像使用任何内置UI视图一样,在XAML或c#标记中使用它。这就是您所需要的全部内容。寻找Xamarin Forms教程- Maui的工作方式相同。查找任何子类化UI类并向其添加BindableProperty的教程,然后显示使用该自定义视图及其自定义属性的XAML。 - ToolmakerSteve
页面和自定义控件的基类。 - H.A.H.
1个回答

7

首先,您可以创建一个名为Name.xaml的新.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="CusComponents.Name">
    <ContentView.Content>

        <StackLayout Padding="10">


            <Label Text="Name" FontAttributes="Bold" />


            <Label Text="First name" />

            <Entry x:Name="FirstName" Placeholder="First name" />


            <Label Text="Last name" />

            <Entry x:Name="LastName" Placeholder="Last name" />


        </StackLayout>

    </ContentView.Content>
</ContentView>

其次,您可以像这样在所需页面中使用它。您需要在 XML 文件顶部添加 xmlns 引用 - 这类似于 C# 文件中的 using 语句。使用示例项目的命名空间结构,这将是 xmlns:custom_components="clr-namespace:CusComponents"

  <?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:custom_components="clr-namespace:CusComponents"
                 x:Class="CusComponents.MainPage">
    
        <custom_components:Name />
    
    </ContentPage>

这里是代码的视图:

enter image description here


这很棒,但是如果您想将不同的绑定传递到此可重用元素的不同实例中怎么办? - Steve W
1
@Steve W - 你需要在可重用控件的 xaml.cs 中创建 BindableProperty。请参考 https://learn.microsoft.com/en-us/dotnet/maui/fundamentals/bindable-properties?view=net-maui-7.0#create-a-bindable-property。 - yurislav

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接