2009-04-17 15 views
26

Cách chính xác để nhận danh sách "trang" thông qua một lớp kế thừa từ System.Configuration.Section nếu tôi đã sử dụng app.config như thế này?Custom app.config Config Section Handler

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 

    <configSections> 
    <section name="XrbSettings" type="Xrb.UI.XrbSettings,Xrb.UI" /> 
    </configSections> 

    <XrbSettings> 
    <pages> 
     <add title="Google" url="http://www.google.com" /> 
     <add title="Yahoo" url="http://www.yahoo.com" /> 
    </pages> 
    </XrbSettings> 

</configuration> 

Trả lời

26

Đầu tiên bạn thêm thuộc tính trong lớp mà kéo dài Mục:

[ConfigurationProperty("pages", IsDefaultCollection = false)] 
[ConfigurationCollection(typeof(PageCollection), AddItemName = "add")] 
public PageCollection Pages { 
    get { 
     return (PageCollection) this["pages"]; 
    } 
} 

Sau đó, bạn cần phải thực hiện một lớp PageCollection. Tất cả các ví dụ tôi đã nhìn thấy khá giống hệt nhau vì vậy chỉ cần sao chép this one và đổi tên "NamedService" thành "Trang".

Cuối cùng thêm một lớp mà kéo dài ObjectConfigurationElement:

public class PageElement : ObjectConfigurationElement { 
    [ConfigurationProperty("title", IsRequired = true)] 
    public string Title { 
     get { 
      return (string) this["title"]; 
     } 
     set { 
      this["title"] = value; 
     } 
    } 

    [ConfigurationProperty("url", IsRequired = true)] 
    public string Url { 
     get { 
      return (string) this["url"]; 
     } 
     set { 
      this["url"] = value; 
     } 
    } 
} 

Dưới đây là một số tác phẩm từ một thực hiện mẫu:

+0

Liên kết đã bị hỏng theo thời gian – Hoppe

+0

@Hoppe nếu bạn muốn triển khai mẫu khác mà tôi đã thực hiện tại đây: http://stackoverflow.com/a/33544322/1955317 – Squazz

3

Ngoài ra, nếu bạn thấy mình tạo các phần cấu hình thường xuyên, có Configuration Section Designer, một nhà thiết kế Ngôn ngữ cụ thể theo miền đồ họa để thiết kế các phần cấu hình.