简体   繁体   English

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

[英]Creating Custom Control Based on Settings in C#

What I want to do is to override Label control and do the followings: 我想做的是覆盖Label控件并执行以下操作:

I defined some key/value pairs in a custom xml file where I like to fetch Text property values of Label Controls and my setting xml file looks like the one below: 我在一个自定义xml文件中定义了一些键/值对,我想在其中获取Label Controls的Text属性值,而我的设置xml文件如下所示:

<label key="lblLabel1" value="Something"/>

When I create a new instance of my custom label control, I will only pass ID and it will find the matching ID key in settings file and set the Text according to what it finds. 当我创建自定义标签控件的新实例时,我只会传递ID ,它将在设置文件中找到匹配的ID键,并根据找到的内容设置Text

And also I like to define my custom control in Source View as well such as below: 我也想在Source View中定义自定义控件,如下所示:

<ccontrol:CLabel ID="lblLabel1"/>

Here I only change set the ID property and Text should be coming from settings.xml file. 在这里,我仅更改ID属性设置,文本应来自settings.xml文件。

How can I do that? 我怎样才能做到这一点?

While I too would suggest using resources, what you are asking for is fairly easy to do. 虽然我也建议使用资源,但是您所要求的很容易做到。

First store your key value pairs in appSettings (Web.config) Link: http://msdn.microsoft.com/en-us/library/610xe886.aspx 首先将您的键值对存储在appSettings(Web.config)链接中: http : //msdn.microsoft.com/zh-cn/library/610xe886.aspx

Then write a control something like this (untested): 然后编写一个类似这样的控件(未经测试):

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