Silverlight中使用設定檔的方法

來源:互聯網
上載者:User

標籤:des   winform   style   io   color   ar   使用   for   sp   

Silverlight作為一個精簡版的.NET framework,沒有為設定檔提供相應的支援。我們無法像在winForm中那樣使用System.Configuration.ConfigurationManager?來訪問app.config中的配置資訊。所以比較好的一個方式就是自己寫一個設定檔管理類ConfigurationManager。

首先,在工程中建立一個XML檔案,取名為app.config,記得放在工程的根目錄,方便後面設定路徑。把Build Action設成Resource,隨便在app.config中寫點東西。

?

<?xmlversion="1.0"encoding="utf-8" ?>

?

<configuration>

?

<appSettings>

?

<addkey="name"value="srzhz"/>

?

<addkey="university"value="Tsinghua University"/>

?

</appSettings>

?

</configuration>

然後要開始建立這個ConfigurationManager類了。

首先在工程上按右鍵點擊Add Reference,之後選擇System.Xml.Linq。(如果沒加的話無法引入命名空間System.Xml.Linq)

然後在ConfigurationManager類中寫入如下代碼

?

using System;

using System.Windows;

using System.Collections.Generic;

using System.Windows.Resources;

using System.IO;

using System.Xml.Linq;

using System.Reflection;

?

namespace SilverlightApplication92

{

///<summary>

?

/// Access appSettings from a configuration file

?

///</summary>

?

///<remarks>Your appConfig file must be in the root of your applcation</remarks>

?

publicstaticclassConfigurationManager

{

static ConfigurationManager()

{

AppSettings = newDictionary<string, string>();

ReadSettings();

}

?

publicstaticDictionary<string, string> AppSettings { get; set; }

?

privatestaticvoid ReadSettings()

{

// Get the name of the executing assemby - we are going to be looking in the root folder for

// a file called app.config

string assemblyName = Assembly.GetExecutingAssembly().FullName;

assemblyName = assemblyName.Substring(0, assemblyName.IndexOf(‘,‘));

string url = String.Format("{0};component/app.config", assemblyName);

StreamResourceInfo configFile = Application.GetResourceStream(newUri(url, UriKind.Relative));

if (configFile != null && configFile.Stream != null)

{

Stream stream = configFile.Stream;

XDocument document = XDocument.Load(stream);

foreach (XElement element in document.Descendants("appSettings").DescendantNodes())

{

AppSettings.Add(element.Attribute("key").Value, element.Attribute("value").Value);

}

}

}

}

}

之後你就可以通過調用這個類來獲得配置資訊了。例如:

String name = ConfigurationManager.AppSettings["name"];

Silverlight中使用設定檔的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.