【发布时间】:2009-06-03 16:18:25
【问题描述】:
我正在为我的 asp.net 网站编写一个自定义用户控件,用于存储日期时间。它有两个属性:
Private _includeTime As Boolean
Private _value As DateTime = Nothing
Public Property IncludeTime() As Boolean
Get
Return _includeTime
End Get
Set(ByVal value As Boolean)
_includeTime = value
End Set
End Property
Public Property SelectedDateTime() As DateTime
Get
Try
_value = DateTime.Parse(txtDate.Text)
If IncludeTime Then
_value.AddHours(Short.Parse(txtHour.Text))
_value.AddMinutes(Short.Parse(txtMinute.Text))
_value.AddSeconds(Short.Parse(txtSecond.Text))
End If
Catch ex As Exception
_value = Nothing
End Try
Return _value
End Get
Set(ByVal value As DateTime)
_value = value
End Set
End Property
我以这种方式调用我的自定义控件:
<my:DateTimeInput runat="server" includetime="true" ID="txtWhen" />
这会正确设置 includetime 属性。
在我的后端代码中,我也在 page_load 上执行此操作:
txtWhen.SelectedDateTime = now
当我逐步调试调试器时,我看到属性被设置,但是当控件本身的 page_load 加载时,属性值被重置为空!
控件的page_load:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
lbltime.Visible = IncludeTime
If SelectedDateTime().CompareTo(Nothing) > 0 Then
txtDate.Text = SelectedDateTime.Date.ToShortDateString()
txtHour.Text = SelectedDateTime.Hour.ToString("D2")
txtMinute.Text = SelectedDateTime.Minute.ToString("D2")
txtSecond.Text = SelectedDateTime.Second.ToString("D2")
End If
End Sub
你知道为什么这个属性会失去它的价值吗?
【问题讨论】: