简体   繁体   English

具有默认值的可空属性的自定义控件

[英]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? 但是,如何在使用自定义控件时将标记中的属性设置为null?

<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. 可以为nullable属性的变通方法(有限制)需要在标记中设置为null。

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). 遗憾的是, <%= %>在null值的情况下不起作用,因为服务器控件上属性的字符串值被计算并解析为其所需类型(只是简单值,而不是表达式)。 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. 现在,问题是:使用数据绑定表达式需要在控件本身或整个页面上执行DataBind()方法。 The easiest way is to be sure, your control's DataBind() method is called. 最简单的方法是确保调用控件的DataBind()方法。

So, this is a workaround with limitation only. 因此,这是一种仅限制的解决方法。

Why not set status to null and only change it when it's set in markup? 为什么不将状态设置为null并仅在标记中设置时更改它?

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 %>' />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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