繁体   English   中英

ASP.NET:具有列表类型的属性的自定义控件(或用户控件) <Something> 。 可以在ASPX源中设置属性吗?

[英]ASP.NET: custom control (or user control) with property of type List<Something>. Can the property be set in the ASPX source?

我有一个用户控件,其属性类型为List<Something>

Private p_myList As New List(Of Guid)
Public Property MyList() As List(Of Guid)
    Get
        Return p_myList
    End Get
    Set(ByVal value As List(Of Guid))
        If value Is Nothing Then Throw New ArgumentNullException()
        p_myList = value
    End Set
End Property

是否可以使用UserControl在页面的aspx源中设置此属性,例如:

<uc1:myUserControl runat="server" MyList="3c7d794e-7645-46e7-bdde-a0bc42679261, 3c7d794e-7645-46e7-bdde-a0bc42679262" />

还是我需要创建一个字符串类型的“兼容性属性”,然后对其进行解析? (我知道我可以通过代码隐藏设置这些值,但我更喜欢在aspx源中进行设置。)

您需要创建一个TypeConvertor

就像是

public class GuidListTypeConverter : System.ComponentModel.TypeConverter 
{ 
    public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, Type sourceType) 
    { 
        return sourceType == typeof(Guid); 
    } 
    public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) 
    { 
        string val = value as string; 

        string[] vals = val.Split(','); 
        System.Collections.Generic.List<Guid> ret = new System.Collections.Generic.List<Guid>();
        foreach (string s in vals)
        {
            ret.Add(Guid.Parse(s));
        }
        return ret;
    } 
}

然后

[TypeConverter(typeof(GuidListTypeConverter))]
public List<Guid> MyList {get;set;}
 QUICK & DIRTY TRICK : make the property public and use the code 
   ((MyPageClassName)this.Page).PropertyName

通过这种方式,您可以提供对与UserControl以及从UserControl到Parent Page和Vice Versa之间的控件的访问。 要使控件可用,请在各自的页面designer.cs文件中将其公开。

****<<Update>>****

感谢您纠正我。 AFAICU,如果要在aspx页面中使用用户控件,则要设置属性。 就像我们设置gridview的DataKeyNames一样,您可以在其中放置多个键字段。 因此,这是一个问题,您如何知道放置在列表中的GUID始终是唯一的。 或者此GUID是固定的,并且来自数据库。 您将如何保持一致性?

我建议,对于此类代码,您可以从aspx处获得更多控制权。

暂无
暂无

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

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