我最近刚刚开始使用 .Net MAUI。但现在我想知道如何使用一段代码,例如我的所有页面上都有一个自制的导航栏,因为在所有 10 个页面上编写相同的代码是没有意义的。我想知道是否有办法创建一个可以像 React 或 Angular 一样重用的组件?
PS:这个问题并不特定于导航栏,而是特定于 .NET MAUI 中代码的一般重用。
到目前为止,我已经观看了有关该主题的各种视频和文章,但是,它更多的是关于自定义控件的,并且对我没有帮助。大多数文章与所传达的内容相对应this https://learn.microsoft.com/en-us/events/dotnetconf-focus-on-maui/code-reuse-with-dotnet-maui视频。我也遇到过this https://stackoverflow.com/questions/73948641/is-it-possible-to-create-global-objects-in-net-maui文章,但它也没有帮助我。
感谢您的帮助 :)
首先,您可以创建一个名为的新 .xaml 文件Name.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>
其次,你可以像这样在你想要的页面中使用它。您需要将 xmlns 引用添加到 XML 文件的顶部 - 这就像 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>
这是代码的视图:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)