私は、この(私はvb.netを使用)
Class MyUserControlA
'Inherits UserControl '(This line will be in your desinger file)
Delegate Sub SomethingEventHandler (sender as object, e as EventArgs) '(assumes you are not going to override event args)
Public Event SomethingEvent as SomethingEventHandler
private _someData as String
Public Readonly Property MyDataGrid as DataGridView
Get
Return DataGridView1 ' this is in the designer form of the user control
End Get
Public Property SomeData as string
Get
return _someData
End Get
Set(value as string)
_someData as string
End Set
End Property
Protected Sub OnSomethingEvent()
RaiseEvent SomethingEvent(Me, EventArgs())
End Sub
'....something happens and you want to raise the event
OnSomethingEvent
End Class
Class MainForm
Implements Form 'designer file
'....other code
Sub MyUserControlA1_SomethingEvent Handles MyUserControlA1.SomethingEvent
'instead of calling a property you could override eventArgs and return the control that way.
MyUserControlB1.OtherDataGridView=MyUserControlA1.MyDataGrid
End Sub
End Class
UserControlBは、次のようにメインフォームを実装するようにそれを行うだろう
Class UserControlB
Inherits UserControl ' designer form
'...other code
private _dataGrid as DataGridView=Nothing
Public Property DataGrid() As DataGridView
Get
Return _dataGrid
End Get
Set(ByVal value As DataGridView)
'only set if null
if _dataGrid is Nothing then _dataGrid = value
End Set
End Property
'do stuff with the control...I would always check for null
function DoSomethingWithDataGrid as integer
if _dataGrid IsNot Nothing then
return _dataGrid.Items.Count
End If
End Sub
End Class
このコードはテストしません。
これはかなり疎結合です。理想的な世界では、メソッドとプロパティでUserControlA DataGridに必要なものをラップし、そのように消費すると思います。しかし、多くのメンバーがいる場合は、DataGridでreferecningしている場合、これは確かに簡単です。
私はこれが完璧なデザインであるとは信じていません。私はまだwinformsアーキテクチャを学んでいます。あなたは何を専門家は思いますか?
セスBスピアマン
私はデリゲートアプローチを試してみましたが、うまくいきました。 (もちろんあなたは言う!)残りの部分とは対照的にかなりエレガントである;) – l3dx