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