请叫雷轰 發表於 2025-4-14 23:03:00

MAUI之Android及Windows跨平台开发之初体验

<h2 id="项目文件">项目文件</h2>
<p>点击此处下载 源代码</p>
<blockquote>
<p>注:</p>
<ol>
<li>本项目使用VS2022开发环境、.NET9框架</li>
<li>Android框架:<br>
最小框架:<code>Android9.0(API Level 28 - Pie)</code><br>
目标框架:<code>Android15.0(API Level 35)</code></li>
<li>Windows框架:<br>
最小框架:<code>10.0.17763.0</code><br>
目标框架:<code>10.0.19041.0</code></li>
<li>如无法编译等情况出现,请确保VS2022是最新的且MAUI工作负载等环境已安装</li>
<li>VS2022在调试Windows桌面应用程序(包含MAUI、WinUI3、UWP)时,暂不支持<code>设计器视图</code>,请使用<code>热重载</code>功能</li>
</ol>
</blockquote>
<h2 id="配置页面">配置页面</h2>
<p><img src="https://img2024.cnblogs.com/blog/580518/202504/580518-20250414221250651-1395302184.png" alt="image" loading="lazy"></p>
<h2 id="mainpage-xaml代码">MainPage XAML代码</h2>
<pre><code class="language-xml">&lt;?xml version="1.0" encoding="utf-8" ?&gt;
&lt;ContentPage
    x:Class="MauiApp1.MainPage"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"&gt;
    &lt;ContentPage.Resources&gt;
      &lt;x:String x:Key="WebSite"&gt;https://www.cnblogs.com/cncc&lt;/x:String&gt;
    &lt;/ContentPage.Resources&gt;
    &lt;Grid&gt;
      &lt;Grid.RowDefinitions&gt;
            &lt;RowDefinition Height="50" /&gt;
            &lt;RowDefinition Height="5" /&gt;
            &lt;RowDefinition Height="40" /&gt;
            &lt;RowDefinition Height="5" /&gt;
            &lt;RowDefinition Height="*" /&gt;
      &lt;/Grid.RowDefinitions&gt;
      &lt;Grid Grid.Row="0" Margin="5"&gt;
            &lt;Grid.ColumnDefinitions&gt;
                &lt;ColumnDefinition Width="1*" /&gt;
                &lt;ColumnDefinition Width="5" /&gt;
                &lt;ColumnDefinition Width="1*" /&gt;
                &lt;ColumnDefinition Width="5" /&gt;
                &lt;ColumnDefinition Width="1*" /&gt;
            &lt;/Grid.ColumnDefinitions&gt;
            &lt;Button
                Grid.Column="0"
                Clicked="Button1_Clicked"
                Text="主页" /&gt;
            &lt;Button
                Grid.Column="2"
                Clicked="Button2_Clicked"
                IsEnabled="{Binding Source={x:Reference CnxyWebView}, Path=CanGoBack}"
                Text="后退" /&gt;
            &lt;Button
                Grid.Column="4"
                Clicked="Button3_Clicked"
                IsEnabled="{Binding Source={x:Reference CnxyWebView}, Path=CanGoForward}"
                Text="前进" /&gt;
      &lt;/Grid&gt;
      &lt;Entry
            x:Name="UrlLabel"
            Grid.Row="2"
            Margin="5,0,5,0"
            IsReadOnly="True"
            SemanticProperties.HeadingLevel="Level1"
            Text="{StaticResource WebSite}" /&gt;
      &lt;ScrollView Grid.Row="4"&gt;
            &lt;WebView
                x:Name="CnxyWebView"
                Navigated="CnxyWebView_Navigated"
                Source="{StaticResource WebSite}"
                VerticalOptions="Fill" /&gt;
      &lt;/ScrollView&gt;
    &lt;/Grid&gt;
&lt;/ContentPage&gt;
</code></pre>
<h2 id="toast通知">Toast通知</h2>
<p>使用了CommunityToolkit.Maui类库(此项针对Android有效),需在MauiProgram.cs文件中配置,代码如下:</p>
<pre><code class="language-csharp">//必须先在Nuget安装CommunityToolkit.Maui包才能使用
//增加了启用Toast通知,使用CommunityToolkit.Maui命名空间
using CommunityToolkit.Maui;
using Microsoft.Extensions.Logging;

namespace MauiApp1
{
    public static class MauiProgram
    {
      public static MauiApp CreateMauiApp()
      {
            var builder = MauiApp.CreateBuilder();
            builder
                //增加此行代码
                .UseMauiCommunityToolkit()

                .UseMauiApp&lt;App&gt;()
                .ConfigureFonts(fonts =&gt;
                {
                  fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                  fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
                });

#if DEBUG
                    builder.Logging.AddDebug();
#endif

            return builder.Build();
      }
    }
}
</code></pre>
<p>增加MyToast.cs文件,用以实际的通知调用,代码如下:</p>
<pre><code class="language-csharp">using CommunityToolkit.Maui.Alerts;
using CommunityToolkit.Maui.Core;

namespace MauiApp1
{
    internal class MyToast
    {
      public static void Show(string message)
      {
            var toast = Toast.Make(message, ToastDuration.Long);
            toast.Show();
      }
    }
}
</code></pre>
<h2 id="mainpage后置代码">MainPage后置代码</h2>
<pre><code class="language-csharp">namespace MauiApp1
{
    public partial class MainPage : ContentPage
    {
      public MainPage()
      {
            InitializeComponent();
      }
      private BroswerStatus broswerStatus;
      private void Announce(WebNavigationResult result)
      {
            string message = string.Empty;
            bool netWorkNoError = false;
            if ((netWorkNoError = result == WebNavigationResult.Success) &amp;&amp; broswerStatus == BroswerStatus.Home)
            {
                message = "已回到主页";
            }
            else
            {
                if(!netWorkNoError)message = "无法网络,请检查!";
            }
            if(string.IsNullOrEmpty(message)) return;
            MyToast.Show(message);
            broswerStatus = BroswerStatus.None;
      }
      private void Button1_Clicked(object sender, EventArgs e)
      {
            if (!(this.Resources["WebSite"] is string webSite)) return;
            broswerStatus = BroswerStatus.Home;
            CnxyWebView.Source = webSite;
      }

      private void Button2_Clicked(object sender, EventArgs e)
      {
            if (!CnxyWebView.CanGoBack) return;
            broswerStatus = BroswerStatus.Back;
            CnxyWebView.GoBack();
      }

      private void Button3_Clicked(object sender, EventArgs e)
      {
            if (!CnxyWebView.CanGoForward) return;
            broswerStatus = BroswerStatus.Forward;
            CnxyWebView.GoForward();
      }

      private void CnxyWebView_Navigated(object sender, WebNavigatedEventArgs e)
      {
            UrlLabel.Text = e.Url;
            Announce(e.Result);
      }

      enum BroswerStatus
      {
            None,
            Home,
            Back,
            Forward
      }
    }
}
</code></pre>
<h2 id="vs2022编辑界面">VS2022编辑界面</h2>
<p><img src="https://img2024.cnblogs.com/blog/580518/202504/580518-20250414223726702-786851130.png" alt="image" loading="lazy"></p>
<h2 id="android调试界面">Android调试界面</h2>
<p>使用<code>vivo x fold 3</code>物理设备,如下:<br>
外屏:<br>
<img src="https://img2024.cnblogs.com/blog/580518/202504/580518-20250414222852955-1572655976.jpg" alt="image" loading="lazy"></p>
<hr>
<p>--------------------------<mark>分割线</mark>--------------------------</p>
<hr>
<p>内屏:<br>
<img src="https://img2024.cnblogs.com/blog/580518/202504/580518-20250414222730612-1274454192.jpg" alt="image" loading="lazy"></p>
<h2 id="windows调试界面">Windows调试界面</h2>
<p><img src="https://img2024.cnblogs.com/blog/580518/202504/580518-20250414223455683-1443962792.png" alt="image" loading="lazy"></p>
<h2 id="可安装或可执行程序">可安装或可执行程序</h2>
<p>Windows桌面应用程序: win10-x64.7z</p>
<blockquote>
<p>密码:30qn</p>
</blockquote>
<p>Android 程序包: net9.0-android35.0.7z</p>
<blockquote>
<p>密码:1n8z</p>
</blockquote><br><br>
来源:https://www.cnblogs.com/cncc/p/18825794
頁: [1]
查看完整版本: MAUI之Android及Windows跨平台开发之初体验