繁体   English   中英

基于C#中的设置创建自定义控件

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM