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

eXo*_*420 9 components dry maui

我最近刚刚开始使用 .Net MAUI。但现在我想知道如何使用一段代码,例如我所有页面上的自制导航栏,因为在所有10个页面上编写相同的代码没有意义。我想知道是否有一种方法可以创建一个可以像 React 或 Angular 一样重用的组件?

PS:这个问题并非特定于导航栏,而是特定于 .NET MAUI 中代码的一般重用。

到目前为止,我已经观看了有关该主题的各种视频和文章,但是,它更多的是关于自定义控件的,并且对我没有帮助。大多数文章与该视频中传达的内容相对应。我也看到了这篇文章,但它对我也没有帮助。

感谢您的帮助 :)

Gua*_*SFT 7

首先,您可以创建一个名为 的新 .xaml 文件Name.xaml。你可以在里面写一些代码。

\n
<?xml version="1.0" encoding="utf-8" ?>\n<ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"\n             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"\n             x:Class="CusComponents.Name">\n    <ContentView.Content>\n\n        <StackLayout Padding="10">\n\n\n            <Label Text="Name" FontAttributes="Bold" />\n\n\n            <Label Text="First name" />\n\n            <Entry x:Name="FirstName" Placeholder="First name" />\n\n\n            <Label Text="Last name" />\n\n            <Entry x:Name="LastName" Placeholder="Last name" />\n\n\n        </StackLayout>\n\n    </ContentView.Content>\n</ContentView>\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n
  <?xml version="1.0" encoding="utf-8" ?>\n    <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"\n                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"\n                 xmlns:custom_components="clr-namespace:CusComponents"\n                 x:Class="CusComponents.MainPage">\n    \n        <custom_components:Name />\n    \n    </ContentPage>\n
Run Code Online (Sandbox Code Playgroud)\n

这是代码的视图:

\n

在此输入图像描述

\n