データバインディングのおべんきょ。その12。
前回は IEnumerable なクラス と BindingSource クラスを使用してデータバインディングしてみました。今回は
ふつーのクラスでやってみる。(ふつーって便利な言葉ですね。)
そうです。IList でもIListSource でもIEnumerable でもないクラスです。以前に使用した WankumaEntertainer クラスでやってみましょうか。
まず、最初に Visual Studio 2005 を使用して Visual Basic で WindowsApplication プロジェクトを作成します。プロジェクト名は「WindowsApplication1」でいいです。するとご存知のとおり、Form1 クラスの作成までやってくれますね。その勝手に出来上がった Form1 に TextBox を配置しておきます。(TextBox1 でいいですよ。)
んでもって、WankumaEntertainer クラスを用意します。
Public Class WankumaEntertainer
Private _name As String = String.Empty
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Public Sub New()
End Sub
Public Sub New(ByVal name As String)
Me.Name = name
End Sub
End Class
で、例によってForm1 はこんなコードになります。その1でやったのと似てますね。(Binding クラスの代わりに BindingSource クラスを使用している感じです。)
Imports System
Imports System.ComponentModel
Imports System.Windows.Forms
Public Class Form1
Private _entertainer As WankumaEntertainer
Private _entertainerBindingSource As BindingSource
Public Sub New()
InitializeComponent()
Me._entertainer = New WankumaEntertainer("とりこびと")
Me.components = New Container
Me._entertainerBindingSource = New BindingSource(Me.components)
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
Me._entertainerBindingSource.DataSource = Me._entertainer
Me.TextBox1.DataBindings.Add("Text", Me._entertainerBindingSource, "Name")
End Sub
End Class
では、さっそく実行してみましょう♪Form1 が表示されたら、TextBox1 に 'とりこびと' って表示されますね。
うっほほ~~い♪
いい!いいですよ!こんな使い方もできるんですね。勉強になりましたね♪
・・・やっぱり・・・終われないのね。
ちょっとこんなの試してみてください。デザイナから Form1 にButton をもう一つ追加して(Button1 で。)Form1 のコードに以下のように書き加えます。
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me._entertainerBindingSource.Add(New WankumaEntertainer("επιστημη"))
End Sub
Button1 をクリックしたら新しい WankumaEntertainer を_entertainerBindingSourceに追加するコードです。どうなるかといいますと(実行すれば分かりますが・・・)
なんだかわからんけど追加できちゃった・・・。(επιστημηさんを追加してしまっていいのかはさておき。)
って、どこに追加されたんでしょう?気になるのでちょっと調べてきました。
どうやらBindingSource.DataSource プロパティ に リスト以外の型(IList でもIListSource でもIEnumerable でもないクラス)を指定すると、内部でその型のリストを作成して管理することになるようなのです。なので、そのリストに対しての追加は可能なのですね。(今回もそのリストに追加されたわけですね。)
なので、試しにデザイナから Form1 にButton をもう一つ追加して(Button2 で。)Form1 のコードに以下のように書き加えます。
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Me._entertainerBindingSource.MoveNext()
End Sub
Button2 をクリックすると、BindingSource のリストの次の要素に移動するコードです。
実行して、Button1 をクリックした後に Button2 をクリックしてみてください。ちゃんとTextBox1に表示されるものも変わりますね。
このように、BindingSource クラスを使用すると、簡単にデータバインドできちゃいます。ただ、今回の場合、一つのインスタンス('とりこびと'のやつ)をバインドしていると思っていたら、いつの間にかリストになってて誰かに勝手に要素を追加されてしまっていたりするかもしれません。ちょっと注意が必要ですね。