ObjectListのデータバインド

テンプレートが曲者、OnItemDataBoundだとうまくFindControlしても引っかからない
→ PreRenderでやる。
DeviceSpecific がサーバコントロールじゃないとFindControlしても引っかからない
DeviceSpecific とは別に Field は必要
→ こっちが本体、DeviceSpecificはデバイスごとの描画方法にすぎない


<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %>

<html xmlns="http://www.w3.org/1999/xhtml" >
<body>
<mobile:Form id="Form1" runat="server">
<mobile:ObjectList ID="ObjectList1" Runat="server" AutoGenerateFields="false">
<Field Name="Name" />
<Field Name="Sex" />
<DeviceSpecific ID="DefaultSpecific" Runat="server">
<Choice>
<ItemTemplate>
<mobile:Label ID="Name" Runat="server" />
<mobile:SelectionList ID="Sex" Runat="server" SelectType="Radio" >
<Item Text="女" Value="0" />
<Item Text="男" Value="1" />
</mobile:SelectionList>
</ItemTemplate>
</Choice>
</DeviceSpecific>
</mobile:ObjectList>
</mobile:Form>
</body>
</html>


Option Strict On
Option Explicit On

Imports System.Data
Imports System.Web.UI.MobileControls
Imports System.Collections.Generic


Partial Class _Default
Inherits System.Web.UI.MobileControls.MobilePage

Private Class Member
Public ID As String
Public Name As String
Public Sex As String
End Class


Public Sub Page_OnLoad() Handles Form1.Load
Dim table = New List(Of Member)(CastEnumerable( _
New Member() With {.ID = "1", .Name = "karua", .Sex = "1"}, _
New Member() With {.ID = "2", .Name = "om", .Sex = "1"}, _
New Member() With {.ID = "3", .Name = "Fujiwo", .Sex = "1"}, _
New Member() With {.ID = "4", .Name = "???", .Sex = "0"} _
))

ObjectList1.DataSource = table
ObjectList1.DataBind()
End Sub

Public Sub ObjectList1_OnPrerender(ByVal sender As Object, ByVal e As EventArgs) Handles ObjectList1.PreRender
Dim list = DirectCast(sender, ObjectList)

If list.DataSource Is Nothing Then Return
If list.Items Is Nothing Then Return

For Each item As ObjectListItem In list.Items
Dim dataItem = TryCast(item.DataItem, Member)
If dataItem Is Nothing Then Return

Dim Name = TryCast(item.FindControl("Name"), Label)
If Name Is Nothing Then Return
Name.Text = dataItem.Name

Dim Sex = TryCast(item.FindControl("Sex"), SelectionList)
If Sex Is Nothing Then Return
For Each SexItem As MobileListItem In Sex.Items
If SexItem.Value = dataItem.Sex Then
SexItem.Selected = True
Exit For
End If
Next

Next
End Sub

Function CastEnumerable(Of T)(ByVal ParamArray items() As T) As IEnumerable(Of T)
Return items
End Function

End Class