简体   繁体   中英

custom control with nullable property that has a default value

I can create a custom control with a default value:

private bool exclue = false;
public bool Exclude { get { return exclue; } set { exclue = value; } }

I can Create the same thing with a nullable property:

private EntityStatuses? status = EntityStatuses.Active;
public EntityStatuses? Status { get { return status; } set { status = value; } }

But how can i then set the property to null in markup when using the custom control?

<MyControls:Control ID="Con" runat="server" Status="?" >

There is a workaround(with limitation) for nullable property that needs to be set to null in the markup.

Unfortunatelly, <%= %> won't work in the case of null value because the string-value of the property on a server-control is evaluated and parsed to its desired type (only simple value, not an expression). But this should work with databinding construction:

<MyControls:Control ID="Con" runat="server" Status="<%#(EntityStatuses?)null %>">

Now, the problem: using a databinding expression needs to execute a DataBind() method either on the control itself or on the entire page. The easiest way is to be sure, your control's DataBind() method is called.

So, this is a workaround with limitation only.

Why not set status to null and only change it when it's set in markup?

private EntityStatuses? status = null;
public EntityStatuses? Status { get { return status; } set { status = value; } }

and

<MyControls:Control ID="Con" runat="server" >

Use two properties with different types:

<MyControls:Control runat="server" StatusString="Active" />

public string StatusString // string! because all values in markup are strings
{
    set
    {
        EntityStatuses s;
        if (Enum.TryParse(value, out s))
            this.status = s; // local variable
    }
}

public EntityStatuses Status
{
    get { return this.status; }
}

or use embedded code block:

<MyControls:Control runat="server" Status='<%= EntityStatuses.Active %>' />

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