標籤: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中使用設定檔的方法