Flag control properties as required in design view

两盒软妹~` 提交于 2019-12-20 03:10:02

问题


I'd like to force the consumer of a control to give a property a value when placing the control on a page.

In VisualStudio when you create an < img > tag without attributes SRC or ALT on a user control, it gets underlined saying that SRC and ALT are required attributes. I assume this is just a special handling of the tag by the editor, but is there a way to define a similar behavior for controls?

If the control had a property defined like this:

public object AProperty
{
    get 
    {
        if (ViewState["AProperty"] == null)
        {
            throw new Exception("AProperty is a required property of this control");
        }
        return ViewState["AProperty"];
    }
    set { ViewState["AProperty"] = value; }
}

Is there a way to use a Custom Attribute or something else that would flag in the designer?


回答1:


You could use the Microsoft.Build.Framework.Required attribute. This would require a value to be set at build time or the build will fail with a message which indicates that the property does not have a value.

I don't believe there is an attribute to indicate that a specific tag must be included in a server control (or at least I don't see any such attribute on the System.Web.UI.HtmlControl.Image class). I believe that the litle underlines are part of the HTML validation of the IDE.

You could always create a custom attribute which throws a warning if a property is missing




回答2:


While Microsoft.Build.Framework.Required is probably the best answer here, for others who stumble upon this and can't use .NET 4.0, you can also use this method:

http://forums.asp.net/t/1238319.aspx



来源:https://stackoverflow.com/questions/787473/flag-control-properties-as-required-in-design-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!