設定 Windows 專案

將新的 Windows 專案新增至現有的 Xamarin.Forms 解決方案

舊Xamarin.Forms版解決方案(或 macOS 上建立的解決方案)將不會有 通用 Windows 平台 (UWP) 應用程式專案。 因此,您必須手動新增UWP專案,以建置 Windows 10 (UWP) 應用程式。

新增 通用 Windows 平台 應用程式

建議在 Windows 10 上使用 Visual Studio 2019 來建置 UWP 應用程式。 如需 通用 Windows 平台 的詳細資訊,請參閱 通用 Windows 平台 簡介。

UWP 適用於 Xamarin.Forms 2.1 和更新版本,Xamarin.Forms2.2 和更新版本支援 Xamarin.Forms .地圖。

如需實用的秘訣, 請參閱疑難解答 一節。

請遵循下列指示,新增將在 Windows 10 手機、平板電腦和桌面電腦上執行的 UWP 應用程式:

1 . 以滑鼠右鍵按兩下方案,然後選取 [新增 > 專案... ],然後新增 空白應用程式 (通用 Windows) 專案:

Add New Project Dialog

2. 在 [新增 通用 Windows 平台 專案] 對話框中,選取應用程式將執行的最低和目標 Windows 10 版本:

New Universal Windows Platform Project Dialog

3. 以滑鼠右鍵按兩下 UWP 專案,然後選取 [ 管理 NuGet 套件... ],然後新增 Xamarin.Forms 套件。 請確定方案中的其他專案也會更新為相同版本的 Xamarin.Forms 套件。

4. 請確定新的 UWP 專案會建置在 [建 > 置組態管理員 ] 視窗中(此項目預設不會發生)。 勾選通用專案的 [建置] 和 [部署] 方塊:

Configuration Manager Window

5. 以滑鼠右鍵按兩下項目,然後選取 [新增 > 參考 ],然後建立應用程式項目的參考 Xamarin.Forms (.NET Standard 或共用專案)。

Reference Manager Dialog

6. 在UWP專案中,編輯 App.xaml.cs ,將方法呼叫包含在 Init 方法內的 OnLaunched 行52左右:

// under this line
rootFrame.NavigationFailed += OnNavigationFailed;
// add this line
Xamarin.Forms.Forms.Init (e); // requires the `e` parameter

7. 在UWP專案中,移除 Grid 元素內含的 Page ,以編輯MainPage.xaml

8. 在 MainPage.xaml中,新增 xmlns 的新 Xamarin.Forms.Platform.UWP專案:

xmlns:forms="using:Xamarin.Forms.Platform.UWP"

9. 在 MainPage.xaml 中,將根 <Page 元素變更為 <forms:WindowsPage

<forms:WindowsPage
...
   xmlns:forms="using:Xamarin.Forms.Platform.UWP"
...
</forms:WindowsPage>

10. 在UWP專案中,編輯MainPage.xaml.cs以移除: Page類別名稱的繼承規範(因為現在會因為上一個步驟中所做的變更而繼承自 WindowsPage ):

public sealed partial class MainPage  // REMOVE ": Page"

11. 在 MainPage.xaml.cs 中,在建構函式中MainPage新增 LoadApplication 呼叫以啟動Xamarin.Forms應用程式:

// below this existing line
this.InitializeComponent();
// add this line
LoadApplication(new YOUR_NAMESPACE.App());

注意

方法的 LoadApplication 自變數是 Xamarin.Forms.Application .NET 標準項目中定義的實例。

12. 從所需的現有平台專案新增任何本機資源(例如圖像檔)。

疑難排解

使用「搭配 .NET 原生工具鏈編譯」時,「目標調用例外狀況」

如果您的 UWP 應用程式參考多個元件(例如第三方控件連結庫,或您的應用程式本身已分割成多個連結庫), Xamarin.Forms 則可能無法從這些元件載入物件(例如自定義轉譯器)。

使用與 .NET Native 工具鏈結進行編譯時,可能會發生這種情況,這是專案 [屬性>建>置一般] 視窗中 UWP app 的選項。

您可以使用 App.xaml.cs呼叫的 Forms.Init UWP 特定多載來修正此問題,如下列程式代碼所示(您應該以程式代碼參考的實際類別取代ClassInOtherAssembly):

// You'll need to add `using System.Reflection;`
List<Assembly> assembliesToInclude = new List<Assembly>();

// Now, add in all the assemblies your app uses
assembliesToInclude.Add(typeof (ClassInOtherAssembly).GetTypeInfo().Assembly);

// Also do this for all your other 3rd party libraries
Xamarin.Forms.Forms.Init(e, assembliesToInclude);
// replaces Xamarin.Forms.Forms.Init(e);

透過直接參考或 NuGet,針對您在 方案總管 中新增做為參考的每個元件新增專案。

相依性服務和 .NET 原生編譯

使用 .NET 原生編譯發行組建無法解析在主要應用程式可執行檔外部定義的相依性服務(例如在不同的專案或連結庫中)。

DependencyService.Register<T>()使用方法來手動註冊相依性服務類別。 根據上述範例,新增如下的 register 方法:

Xamarin.Forms.Forms.Init(e, assembliesToInclude);
Xamarin.Forms.DependencyService.Register<ClassInOtherAssembly>(); // add this