[英]How to create custom pages in .Net Maui?
我有一个自定义页面模板,定义如下:
第1页:
<?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"
x:Class="MyApp.Resources.Controls.Page1"
Title="Page1">
<ContentPage.ControlTemplate>
<ControlTemplate>
<Grid RowDefinitions="auto,*">
<Label Text="Label 1" Grid.Row="0">
<!-- Content of page 1 -->
<ContentPresenter Grid.Row="1" />
</Grid>
</ControlTemplate>
</ContentPage.ControlTemplate>
</ContentPage>
所有从 Page1 继承的页面都有"Label 1" 。 所以这工作正常。
现在我需要创建一个继承自Page1的新自定义页面。 基本上向模板添加新元素并保留 Page1 中已有的元素。
第2页:
<?xml version="1.0" encoding="utf-8" ?>
<Controls:Page1 xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MyApp.Resources.Controls.Page2"
xmlns:Controls="clr-namespace:MyApp.Resources.Controls"
Title="Page2">
<Controls:Page1.ControlTemplate>
<ControlTemplate>
<Grid RowDefinitions="auto,*" >
<Label Text="Label 2" Grid.Row="0">
<!-- Content of page 2 -->
<ContentPresenter Grid.Row="1"/>
</Grid>
</ControlTemplate>
</Controls:Page1.ControlTemplate>
</Controls:Page1>
现在从Page2继承的页面没有"Label 1" 。 他们只有“标签 2”。 虽然我希望这些页面同时具有"Label 1"和"Label 2" 。
我该如何解决?
您可以做什么的简短版本:
制作自定义控件 class(假设在命名空间控件中),继承 ContentView
公共 class MyControl:ContentView
在 ResourceDictionary 中,添加控件模板,并在其中添加您的 VisualElements。
< ControlTemplate x:Key="MyControlTemplate" >... </ControlTemplate >
在您的视图中,添加您的控件:
< controls:MyControl ControlTemplate="{StaticResource MyControlTemplate}" />
控件在哪里:
xmlns:controls="clr-namespace:MyNamespace.Controls"
现在您的用户界面可以在您想要的每个页面中重复使用。 (并将命令/属性绑定到它,使用不同的模板等......)
最好的部分是您在一个地方进行更改,并且它会在整个项目中进行更改。
您的解决方案工作正常。 将 page2 修改为标准页面并继承 page1。 现在 Page2 将同时显示标签 Label 1 和 Label 2。
<Controls:Page1 x:Class="MyApp.Resources.Controls.Page2"
Title="Page2">
<Grid RowDefinitions="auto,*" >
<Label Text="Label 2" Grid.Row="0">
<!-- more xaml here -->
</Grid>
</Controls:Page1>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.