1
我的頁面元素訪問proprties集合屬性「name」時遇到問題。 Pages有一個包含屬性的頁面字段的集合可以有人看看我的代碼,並告訴我如何獲得每個頁面上具有name屬性的頁面並訪問其值。目前我的代碼只返回頁面加載沒有任何錯誤,所以我不知道發生了什麼以及如何獲取屬性字段。自定義WebConfig返回集合屬性的部分
<configSections>
<sectionGroup name="site" type="MyProject.Configuration.Site">
<section name="pages" type="MyProject.Configuration.Pages"/>
</sectionGroup>
</configSections>
<site>
<pages>
<page name="test">
</page>
</pages>
</site>
類:
public class Site : ConfigurationSection
{
[ConfigurationProperty("pages")]
[ConfigurationCollection(typeof(PageCollection), AddItemName="page")]
public PageCollection Pages
{
get
{
return base["pages"] as PageCollection;
}
}
}
public class PageCollection : ConfigurationElementCollection
{
public PageCollection()
{
PageElement element = (PageElement)CreateNewElement();
BaseAdd(element); // doesn't work here does if i remove it
}
protected override ConfigurationElement CreateNewElement()
{
return new PageElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((PageElement)element).Name;
}
public PageElement this[int index]
{
get
{
return (PageElement)BaseGet(index);
}
set
{
if (BaseGet(index) != null)
{
BaseRemoveAt(index);
}
BaseAdd(index, value);
}
}
}
public class PageElement : ConfigurationElement
{
public PageElement() { }
[ConfigurationProperty("name", IsKey=true, IsRequired=true)]
public string Name
{
get
{
return (string)base["name"];
}
set
{
base["name"] = value;
}
}
}
代碼來訪問我的屬性:
Pages pageSettings = ConfigurationManager.GetSection("site/pages") as Pages;
lblPage.Text = pageSettings.Page[0].Name;
我改正了這一點,我仍然沒有收集屬性值集合 – ONYX 2012-01-01 01:52:52
我更新了我的代碼,除了在類指令中的PageCollection類中它有效。 BaseAdd(元素)不起作用,但如果我刪除它,它的作品,你知道如何修復我的代碼,所以我可以使其正常工作 – ONYX 2012-01-01 03:00:47
@KDM:你不應該在類指令(又名構造函數)中有任何代碼。配置處理將自動添加適當的PageElements,因此您不需要那樣做。 – 2012-01-01 03:03:21