简体   繁体   中英

How to initialize Custom control attribute (property) of complex type (struct\ class)

I have a custom control in asp.net My custom control have a class member of type Size (value type with Width and Height inner members). I would like to initialize this member from the .aspx file.

The ideal solution will be (this line will not pass compilation):

<CustomControl:MyCtrl runat="server" ID="MyCtrlID" MaxSize="{Width=200, Height=400}"/>

The code at the .cs file:

public partial class MyCtrl: System.Web.UI.UserControl
{
    public System.Drawing.Size MaxSize { get; set;}

    // Class logic...
}

Of curse I can solve this issue by adding logic to the setter (at the c# code), like this:

private System.Drawing.Size m_MaxSize;
public string MaxSize 
{ 
    set 
    { 
        string[] sizes = value.Split(",");
        m_MaxSize.Width = sizes[0];
        m_MaxSize.Height = sizes[1];
    }
}

But do we have any asp.net syntax to do this for us?, any help is greatly appreciated.

Since Size Structure uses SizeConverter Class to convert and access Size properties, the following example demonstrates how to properly delcare MaxSize property:

<CustomControl:MyCtrl runat="server" ID="MyCtrlID" MaxSize="200, 400"/>

About Type Converters

Type Converters

provides a unified way of converting types of values to other types, as well as for accessing standard values and subproperties.

ASP.NET uses type converters at run time to serialize and deserialize objects stored in control state and in view state, follow Type Converter Example for a more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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