MAUI中实现构建跨平台原生控件

2022-04-17 01:34:54

简介

MAUI中使用Handler体系来处理不同平台的原生控件实现, 即对应的, 如果我们想要创建控件, 只需要创建基于不同平台的Handler即可。

那么下面主要教大家如何通过创建Handler(事件处理程序)来构建自己的控件。

开始

下面, 将通过创建一个进度条控件案例, 来演示如何在MAUI项目中创建平台控件并且使用它。

假设控件包含基础的三项功能, 进度条颜色(Foreground)、进度条当前值(Value)、进度条模式(Indeterminate)

1.第一步(声明控件类)

首先, 创建MyProgressBar类, 定义对应的依赖属性

internal class MyProgressBar : View    {        public static readonly BindableProperty ForegroundProperty =            BindableProperty.Create(nameof(Foreground),                typeof(Color),                typeof(MyProgressBar),                Colors.Transparent);        public static readonly BindableProperty ValueProperty =           BindableProperty.Create(nameof(Value),               typeof(double),               typeof(MyProgressBar),               0.0);        public static readonly BindableProperty IndeterminateProperty =           BindableProperty.Create(nameof(Indeterminate),               typeof(bool),     UXqIrBEq          typeof(MyProgressBar),               false);        public Color Foreground        {            get { return (Color)GetValue(ForegroundProperty); }            set { SetValue(ForegroundProperty, value); }        }                 public double Value        {            get { return (doar.ttf", "OpenSansRegular");                })                .ConfigureMauiHandlers(handler =>                {                  handler.AddHandler(typeof(MyProgressBar), typeof(MyProgressBarHandler));                });              return builder.Build();        }

6.界面中,分别声明MAUI原生控件与自定义控件

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"             x:Class="MAUIRender.MainPage"             xmlns:my="clr-namespace:MAUIRender"              xmlns:ctor="clr-namespace:MAUIRender.Controls"              BackgroundColor="{DynamicResource SecondaryColor}">    <Grid>        <StackLayout>            <ProgressBar                   Progress="30" ProgressColor="Red"/>                        <ctor:MyProgressBar                 Indeterminate="True"                Value="600"  Foreground="Green" />        </StackLayout>    </Grid></ContentPage>

运行实际效果:

MAUI中实现构建跨平台原生控件

总结

通过利用Handler来处理不同平台控件的行为, 与控件本身解耦并且更加容器支持更多的平台。

到此这篇关于MAUI中实现构建跨平台原生控件的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持我们。