[英]Creating Custom Control Based on Settings in C#
我想做的是覆蓋Label控件並執行以下操作:
我在一個自定義xml文件中定義了一些鍵/值對,我想在其中獲取Label Controls的Text屬性值,而我的設置xml文件如下所示:
<label key="lblLabel1" value="Something"/>
當我創建自定義標簽控件的新實例時,我只會傳遞ID
,它將在設置文件中找到匹配的ID鍵,並根據找到的內容設置Text
。
我也想在Source View中定義自定義控件,如下所示:
<ccontrol:CLabel ID="lblLabel1"/>
在這里,我僅更改ID屬性設置,文本應來自settings.xml文件。
我怎樣才能做到這一點?
雖然我也建議使用資源,但是您所要求的很容易做到。
首先將您的鍵值對存儲在appSettings(Web.config)鏈接中: http : //msdn.microsoft.com/zh-cn/library/610xe886.aspx
然后編寫一個類似這樣的控件(未經測試):
using System;
using System.Configuration;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Web
{
public class SpecialLabel : Label
{
protected override void OnLoad (EventArgs e)
{
base.OnLoad (e);
//get value from appsettings
if(!string.IsNullOrEmpty(this.ID)) {
Configuration rootWebConfig1 = WebConfigurationManager.OpenWebConfiguration(null);
if (rootWebConfig1.AppSettings.Settings.Count > 0)
{
KeyValueConfigurationElement customSetting = rootWebConfig1.AppSettings.Settings[this.ID];
if (customSetting != null)
this.Text = customSetting.Value;
}
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.