MHF*_*MHF 5 asp.net web-controls
我对默认值属性有疑问。
当我在设计模式下将控件添加到页面时,默认值不起作用。这是我的代码:
[DefaultProperty("Text")]
[ToolboxData("<{0}:KHTLabel runat=server key=dfd></{0}:KHTLabel>")]
public class KHTLabel : Label ,IKHTBaseControl
{
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("KHT")]
[Localizable(true)]
public string Key
{
get
{
String s = (String)ViewState["Key"];
return ((s == null) ? String.Empty : s);
}
set
{
ViewState["Key"] = value;
}
}
protected override void RenderContents(HtmlTextWriter writer)
{......
Run Code Online (Sandbox Code Playgroud)
但是,在设计模式下,当我从工具箱添加控件时,键不存在
<cc1:KHTLabel ID="KHTLabel1" runat="server"></cc1:KHTLabel>
Run Code Online (Sandbox Code Playgroud)
[DefaultValue]恐怕这不是该属性的作用。它的作用是允许 Visual Studio 设计器(特别是“属性”网格)确定默认显示的内容,以及如何知道在与默认值不同时将值显示为粗体。
您可以在代码中保留“KHT”值作为默认值,这取决于您。我 2008 年发表的博客文章中有一些相关细节。
以下代码相当基本,我无法验证它是否可以编译,但它应该让您了解如何处理“强制”将 s 的值DefaultValueAttribute放入ViewState:
private string GetDefaultAttributeValueForProperty(string propertyName)
{
var attributesForProperty = (from prop in typeof(KHTLabel).GetProperties()
where prop.Name == propertyName
select System.Attribute.GetCustomAttributes(prop)).First();
var defaultValueAttribute = (from attr in attributesForProperty
where attr.GetType() == typeof(DefaultValueAttribute)
select ((DefaultValueAttribute)attr).Value).FirstOrDefault();
return Convert.ToString(defaultValueAttribute);
}
public KHTLabel()
{
ViewState["Key"] = GetDefaultAttributeValueForProperty("Key");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2494 次 |
| 最近记录: |