Maui's Learning Path (2)-Setting up

Maui's Learning Path (2)-Setting up

Not just MAUI, this article is very useful

最后更新 6/23/2022 11:29 PM
轩研 Maui开发者
预计阅读 9 分钟
分类
MAUI
标签
.NET MAUI

In the previous article, we gave a basic introduction to Maui. In theory, this article should create the first Maui application so that we can conduct a detailed evaluation and gradually deepen it.

如果你需要进行 Maui 首个应用的创建,那么欢迎访问.NET MAUI 创建移动应用—Get Start,以及MAUI 与 Blazor 共享一套 UI,媲美 Flutter,实现 Windows、macOS、Android、iOS、Web 通用 UI,本文的重点不是创建 Maui 的应用而是如何更好的配置 Maui 的工程。

Solving annoying "obj"

There has been a problem that has deeply troubled us for a long time. Whenever a c#program is compiled, it will always generate an "obj" directory under the project folder. It is very eye-catching. Once git is submitted, we need to eliminate it one by one (if there are many projects, it will be worse than death). This is very annoying. So can we move him?

Before completing the following settings, please follow me to do the following:

  1. Create a C++ project (we don't want to develop C++ programs but it will have a very positive effect on our subsequent learning)

这里我创建了一个C++ Console工程

创建一个 xml 文件,把他重命名为Directory.build.props(这个名称随意,只是喜欢这么叫)

双击Directory.build.props文件打开并编辑,删除 xml 中所有内容,在该文件中添加如下设置

<Project>
 <PropertyGroup>
  <BaseIntermediateOutputPath>$(MSBuildThisFileDirectory).vs\$(SolutionName)\Intermediate\$(MSBuildProjectName)\</BaseIntermediateOutputPath>
 </PropertyGroup>
</Project>

这里我不会介绍BaseIntermediateOutputPath这个设置字段的用意,如果你需要知道请访问:常用的 MSBuild 项目属性 - MSBuild | Microsoft Docs(如果你是用的是 vs2022 for mac,那么很抱歉的告诉你他不支持这个属性,我在官方的 issue 翻阅过这个 bug 早在 vs2019 for mac 就存在,只不过微软视而不见),所以为了避免尴尬的事情发生,我们需要加上一个条件判定,这个条件就是当操作系统是 windows 时这个设置项才生效

 <!--这个属性可以让你跟obj say goodbye-->
 <PropertyGroup Condition="$([MSBuild]::IsOSPlatform('windows'))">
  <BaseIntermediateOutputPath>$(MSBuildThisFileDirectory).vs\$(SolutionName)\Intermediate\$(MSBuildProjectName)\</BaseIntermediateOutputPath>
 </PropertyGroup>

Here I have to say that the Microsoft VS team is really powerful. You only need to install VS to open the same code on different platforms, and you don't need to make other compilation settings.

we're family

当一个解决方案(Solution)存在多个项目时(csproj),我们一定希望所有项目生成的 dll 或者 exe 以及配置文件都统统编译生成到一个固定的地方,通常我们都会手动设置编译生成路径,这个方式极不推荐因为你所做的选择总是一个不可靠的路径(如果这是一个团队合作的项目),我们只需要做如下一点点改变(该设置仍然是在Directory.build.props中进行添加)

<PropertyGroup>
  <!--这个属性可以让你规划统一生成路径-->
  <OutputPath>$(MSBuildThisFileDirectory)Binary\</OutputPath>
 </PropertyGroup>

Let him be everything

我们常常有这样的思考,能不能在一个地方配置,所有工程都能有改变,比如 Nullable 的启用,比如 C#的语言版本等等,那么只需要对Directory.build.props增加如下配置

<PropertyGroup>
  <!--这个属性可以让你规划统一生成路径-->
  <OutputPath>$(MSBuildThisFileDirectory)Binary\</OutputPath>
  <LangVersion>latest</LangVersion>
  <Nullable>enable</Nullable>
  <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

can't live without you

Are you confused, when all projects (csproj) under my Solution need to use the same package, can I just do a package reference once? Please follow me next:

  1. 创建一个 xml(这已经很熟悉了),将他改名为Directory.build.targets(我喜欢这个名字)

  1. Directory.build.targets中的内容修改为:
<Project>
 <!--这样的设计可以让你当前解决方案下的所有项目都能获取到package-->
 <ItemGroup>
  <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
 </ItemGroup>
</Project>

Make him proactive

By completing the above settings, you have become a solution manager, but that's not enough. We all know that.net6 or c#10 introduces file-scoped namespaces. You only need to write a namespace xxx. There are fewer curly braces to make your code look more concise. Unfortunately, if you don't make any changes, then it will never be so proactive. The default class you create must look like this:

namespace MauiLib1
{
   internal class Class2
   {
   }
}

Please follow me and he will become more obedient:

  1. Create an editorconfig

  1. Double-click. editorconfig to open the File scped configuration (If you open the directly open text instead of the settings interface, don't worry, just complete subsequent settings after the next restart)

    • You have completed some efficient settings. Only when you close vs and reopen the solution will all the above settings take effect. Don't forget to delete the compilation garbage that has already been generated, such as the following: **

    • At this time, the new class you create becomes like this: **
namespace MauiLib1;
internal class Class3
{
}
    • Recompile the solution. All your dLs and exEs have been generated under binary, and every csproj directory is quite clean (note that the above settings are invalid for c++ projects. C++ projects need to be configured separately and will not be introduced here. **

don't forget he

After completing the above settings, none of the c++ project we just created seems to have any effect. Yes, the c++ project is just for you to have a look (I am just playing with you). Next, what we need to discuss is how do you know this (as shown in the picture)

In fact, these are some built-in macro definitions for vs. We can't know why these macros exist in c#. At this time, we need to use c++ projects.

    • Here you can see these various setting fields and the values displayed by the corresponding macro. This macro belongs to vs, so the c#project is also valid **

Give too much

Next, we will discuss some in-depth settings of Maui. On Windows, I always compile android, ios, and maccatalyst by default. If there are too many, I don't need them at all. Then you can modify TargetFrameworks (such as this)

    • Note: Once this is modified, it means that you can no longer choose another platform to check whether the code is correct (code reliability will not be guaranteed)(the most intuitive appearance of removing the compilation settings on other platforms is that the compilation becomes abnormally fast)**

Make her loyal

When I generate a Window application, we need to reference a Window platform-related package, such as the Pvoke.User32 we are familiar with. Obviously, this library is only suitable for the Windows platform. Although other platform references will not cause compilation errors in the past, there will inevitably be an irrelevant dll in the package file (maybe not I haven't tested it, I guess it does). This is something we don't want to see, so we want to do this:

<!--这是一个专属于Windows的设定,让他成为Windows忠诚的伴侣-->
<ItemGroup Condition="$(TargetFramework.Contains('-windows'))">
  <!-- Required - WinUI does not yet have buildTransitive for everything -->
  <PackageReference Include="PInvoke.User32" Version="0.7.104" />
</ItemGroup>

They need isolation.

在编写代码时,我们通常会遇到我的部分代码是适用于 Windows 的而不适用于其他平台,此时你可以使用编译宏命令 #if #elif #else #endif

public static MauiApp CreateMauiApp()
{
   var builder = MauiApp.CreateBuilder();
   builder
    .UseMauiApp<App>()
    .ConfigureFonts(fonts =>
    {
     fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
     fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
    });

#if WINDOWS
    string? name = "Windows";
#elif MACCATALYST
    string? name = "Mac";
#else
   string? name = "Mobile";
#endif
   return builder.Build();
}

Let him be himself

We are looking forward to running Windows applications written in Maui directly by double-clicking exe (which was a luxury in the past). Now you only need to modify two settings (in the project file csproj of the main program), adding the following two configurations (Anycpu compilation is no longer supported after using this configuration, so we do a conditional compilation):

<!--这个方案可以让你的Maui在Windows下生成的exe做回自己-->
<PropertyGroup Condition="'$(Platform)' != 'AnyCPU' And $(TargetFramework.Contains('-windows'))">
  <!-- Unpack : SelfContainedDeployment for winui3 -->
  <WindowsPackageType>None</WindowsPackageType>
  <WindowsAppSDKSelfContained>true</WindowsAppSDKSelfContained>
</PropertyGroup>

Multi-compilation platform configuration

In the previous change, because exe needs to be run directly, the added settings are completely unsupported in the anycpu compilation environment, so you need to configure a multi-platform compilation solution (such as x64 x86 ARM64, etc.). The configuration method is as follows:

  1. Click Configuration Manager

  1. Added compilation for X64 and other platforms

    • To sum up, we have completed most of the settings in the solution (Solution) and project (csproj). Making these settings well will make some of your work easier. **

以上设置都已上传github

Keep Exploring

延伸阅读

更多文章
同分类 / 同标签 4/11/2024

NET MAUI Open Source Free UI Toolkit- Uranium

There have been friends who have been leaving messages on the background of the Weixin Official Accounts asking me to share the UI framework related to. NET MAUI. Today, Dayao shared an open source and free UI toolkit: Uranium.

继续阅读
同分类 / 同标签 1/12/2023

Maui Blazor uses a camera

Since the interface in Maui Blazor is rendered by WebView, it cannot be obtained when using the Android camera again, because the native camera needs to be bound with interface components.

继续阅读