我想知道是否可以将一个字符串数组发送到标签的属性
<SampleTag:Form
runat="server"
ID="sampleform1"
Items={item1,item2,item3,item4}
>
</SampleTag:Form>
这不起作用,因为它将“{item1,item2,item3,item4}”作为字符串发送给该类。
答案 0 :(得分:3)
最好在代码背后执行此操作
<SampleTag:Form runat="server" ID="sampleform1"></SampleTag:Form>
sampleform1.Items = new { item1, item2, item3, item4 };
答案 1 :(得分:2)
您可能必须向属性添加属性,但您应该能够继续使用xml端来执行分配:
<SampleTag:Form
runat="server"
ID="sampleform1">
<Items ID="item1">item1</Items>
<Items ID="item2">item2</Items>
<Items ID="item3">item3</Items>
<Items ID="item4">item4</Items>
</SampleTag>
本文可能会提供一些额外的见解:http://msdn.microsoft.com/en-us/library/aa478964.aspx
答案 2 :(得分:0)
我知道你已经接受了答案,但我想让你知道你可以使用类型转换器做你想做的事情。我更喜欢这种方法,因为它使控件更加设计友好,更容易让其他人使用。
使用:(对不起VB代码......)
<cc1:ServerControl1 ID="ServerControl11" runat="server" Items="Testing,Test2,Test3,Test4,Test5" />
<强>代码:强>
关键是在属性上使用TypeConverter属性(在此类之后查看定义)。
Public Class ServerControl1
Inherits WebControl
<TypeConverter(GetType(StringToArray))> _
Public Property Items() As String()
Get
If ViewState("Items") IsNot Nothing Then
Return ViewState("Items")
Else
Return New String() {}
End If
End Get
Set(ByVal value As String())
ViewState("Items") = value
End Set
End Property
Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
MyBase.Render(writer)
For Each s As String In Items
writer.Write(String.Format("-{0}<br/>", s))
Next
End Sub
End Class
Public Class StringToArray
Inherits TypeConverter
Public Overloads Overrides Function CanConvertFrom(ByVal context As ITypeDescriptorContext, ByVal sourceType As Type) As Boolean
If sourceType Is GetType(String) Then
Return True
End If
Return MyBase.CanConvertFrom(context, sourceType)
End Function
Public Overloads Overrides Function ConvertFrom(ByVal context As ITypeDescriptorContext, ByVal culture As CultureInfo, ByVal value As Object) As Object
If TypeOf value Is String Then
Dim v As String() = CStr(value).Split(New Char() {","c})
Return v
End If
Return MyBase.ConvertFrom(context, culture, value)
End Function
End Class