在 Xamarin.Forms Xaml 專案中讀取 app.config 檔案

雖然每個移動平臺都提供了自己的設定管理 API,但沒有內建的方法可以從一個好的 .net 風格的 app.config xml 檔案中讀取設定。這是由於一系列充分的理由,特別是 .net 框架配置管理 api 在重量級方面,並且每個平臺都有自己的檔案系統 api。

因此,我們構建了一個簡單的 PCLAppConfig 庫,非常好的 nuget 打包供你立即使用。

該庫使用了可愛的 PCLStorage

此示例假定你正在開發 Xamarin.Forms Xaml 專案,你需要從共享檢視模型中訪問設定。

  1. 在每個平臺專案上初始化 ConfigurationManager.AppSettings,緊跟在’Xamarin.Forms.Forms.Init’語句之後,如下所示:

iOS(AppDelegate.cs)

global::Xamarin.Forms.Forms.Init();
ConfigurationManager.Initialise(PCLAppConfig.FileSystemStream.PortableStream.Current);
LoadApplication(new App());

Android(MainActivity.cs)

global::Xamarin.Forms.Forms.Init(this, bundle);
ConfigurationManager.Initialise(PCLAppConfig.FileSystemStream.PortableStream.Current);
LoadApplication(new App());

UWP / Windows 8.1 / WP 8.1(App.xaml.cs)

Xamarin.Forms.Forms.Init(e);
ConfigurationManager.Initialise(PCLAppConfig.FileSystemStream.PortableStream.Current);
  1. 將 app.config 檔案新增到共享 PCL 專案,並新增 appSettings 條目,就像處理任何 app.config 檔案一樣
<configuration>
    <appSettings>
        <add key="config.text" value="hello from app.settings!" />
    </appSettings>
</configuration>
  1. 將此 PCL app.config 檔案新增所有平臺專案上的連結檔案。對於 android,確保將構建操作設定為 AndroidAsset ,對於 UWP,將構建操作設定為 Content

  2. 訪問你的設定:ConfigurationManager.AppSettings["config.text"];