开发者

Setting property default values for a Web User Control

开发者 https://www.devze.com 2022-12-26 19:53 出处:网络
I am trying to build a web user control and set some default values for its properties in the code-behind like this:

I am trying to build a web user control and set some default values for its properties in the code-behind like this:

[DefaultValue(typeof(int), "50")]
public int Height { get; set; }

[DefaultValue(typeof(string), "string.Empty")]
public string FamilyName { get; set; }

[DefaultValue(typeof(Color), "Orange")]
public System.Drawing.Color ForeColor { get; set; }

When I add the user control to the page and call it without any propert开发者_运维技巧ies:

<uc1:Usercontrol ID="uc" runat="server" />

the default values are not set and every property is 0 or null.

What am I doing wrong?

Thanks.


The DefaultValueAttribute will not set any value for your property, it only serves as a hint for designers and whatnot.

If you want a default value, you'll have to set it in the constructor (or even better, in a property initializer, which were added in C# 6). If you're storing your stuff in the ViewState, you'll need to expand those property definitions and make them access the ViewState. Then set the default values for the properties in the OnInit method to avoid persisting them on the client side.


From http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx

Note A DefaultValueAttribute will not cause a member to be automatically initialized with the attribute's value. You must set the initial value in your code.

In other words, the DefaultValueAttribute just gives you a place to declare what you want the value to be. You still have to write code to populate the value from the attribute.

0

精彩评论

暂无评论...
验证码 换一张
取 消