dotnet 使用 XWT 構建跨平台客戶端 入門篇


本文告訴大家如何入門開始開發一個基於 mono 組織開源的 XWT 跨平台客戶端 UI 框架的應用,本文的 xwt 是在 GitHub 上完全開源的,基於 MIT 協議的,底層采用 GTK# 的 UI 框架

此 xwt 在設計上是通過 mono 進行跨平台運行的,而非采用 dotnet core 方式進行跨平台運行的,因此暫時只能使用 dotnet framework 4.7.2 版本,而不支持 dotnet core 版本。至少在 2021.08.09 依然是不支持在 dotnet core 運行

在開始之前,將會因為 xwt 依賴 GTK# 的環境而需要先部署 GTK# 的開發環境

官網 下載 GTK# 的 x86 安裝包或 mono x86 的應用

安裝到默認路徑,也就是在 C:\Program Files (x86)\GtkSharp\2.12\bin 路徑,默認安裝的時候會加入到環境變量。詳細請參閱 Xamarin 使用 GTK 提示找不到 libglib-2.0-0.dll 找不到

接着打開 VisualStudio 完成 .NET Framework 4.7.2 和 dotnet core 負載(為了mono的默認安裝)的安裝,以及桌面開發 (xwt 可以基於 wpf 版本)的安裝

以上就是所有的環境部署步驟,對於大部分開發者,只需要去下載 GtkSharp 安裝即可。我依然推薦安裝到默認路徑,無論是 GtkSharp 還是 VisualStudio 都放在默認路徑

新建一個 dotnet core 控制台項目

修改 csproj 項目文件,替換為如下代碼

<project sdk="Microsoft.NET.Sdk">

  <propertygroup>
    <outputtype>Exe</outputtype>
    <targetframeworks>net472;netcoreapp3.1</targetframeworks>
    <platformtarget>x86</platformtarget>
  </propertygroup>

  <itemgroup>
    <none include="C:\Program Files %28x86%29\GtkSharp\2.12\bin\*.dll" link="%(FileName).dll">
      <copytooutputdirectory>PreserveNewest</copytooutputdirectory>
    </none>
  </itemgroup>

  <itemgroup>
    <packagereference include="Xwt.Gtk" version="0.2.247">
  </packagereference></itemgroup>

</project>

以上代碼就是設置框架是 .NET Framework 4.7.2 和 dotnet core 3.1 兩個版本,當然當前是不能跑 dotnet core 3.1 的版本的。接着因為 GTK# 當前只支持客戶端的 x86 版本,因此需要設置 PlatformTarget 作為 x86 版本

默認是不會去找到 GTK Sharp 的 DLL 內容的,因此通過如下代碼引用所有的 DLL 用來輸出

  <itemgroup>
    <none include="C:\Program Files %28x86%29\GtkSharp\2.12\bin\*.dll" link="%(FileName).dll">
      <copytooutputdirectory>PreserveNewest</copytooutputdirectory>
    </none>
  </itemgroup>

打開 Program.cs 文件,添加如 xwt 官方開源倉庫 https://github.com/mono/xwt 的例子

        [STAThread]
        static void Main(string[] args)
        {
            Application.Initialize(ToolkitType.Gtk);

            var mainWindow = new Window()
            {
                Title = "Xwt Demo Application",
                Width = 500,
                Height = 400
            };
            mainWindow.Show();
            Application.Run();
        }

選擇 .NET Framework 4.7.2 版本,嘗試運行一下應用。默認即可看到顯示了窗口

本文所有代碼在 githubgitee 上完全開源

不嫌棄麻煩的話,還請自行下載代碼,自己構建。可以通過如下方式獲取本文的源代碼,先創建一個空文件夾,接着使用命令行 cd 命令進入此空文件夾,在命令行里面輸入以下代碼,即可獲取到本文的代碼

git init
git remote add origin https://gitee.com/lindexi/lindexi_gd.git
git pull origin 11125ca50dc91e50cf581c36476f03b853bc7ef8

以上使用的是 gitee 的源,如果 gitee 不能訪問,請替換為 github 的源

git remote remove origin
git remote add origin https://github.com/lindexi/lindexi_gd.git

獲取代碼之后,進入 LarwearceceyokuDokealuwo 文件夾


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM