检查列表是否已被修改

时间:2013-11-30 04:44:11

标签: vb.net forms visual-studio controls panel

我试图基本上让FlowLayoutPanel只接受我创建的继承Button的自定义控件。所以我已经隐藏了Controls属性,并且我创建了自己的属性,但是我没有将它声明为ControlsCollection,而是将其声明为列表:

Public Shadows ReadOnly Property Controls() As ControlCollection
    Get
        Return MyBase.Controls
    End Get
End Property

Private itms As New List(Of MenuItem)
Public Property Items() As List(Of MenuItem)
    Get
        Return itms
    End Get
    Set(value As List(Of MenuItem))
        itms = value
    End Set
End Property

我感到困惑的是如何检查Items()属性是否已被修改,我可以调用以下内容:

 Me.Controls.Clear : Me.Controls.AddRange(itms.ToArray())

1 个答案:

答案 0 :(得分:0)

由于问题在于通过公开Items,可以添加内容,您可以删除它并公开AddItemRemoveItem类型方法:

Private _dataChanged As Boolean = False
Public Function AddItem(ByVal mi As MenuItem) As Integer
    _items.Add(mi)
    _dataChanged = True
    return _items.Count
End Function

作为List(Of T),它可以防止添加非T项目,但是您的控件实际上并没有完全掌控项目列表,而是以这种方式公开。另一种方法可能是使用包含ListChanged事件的BindingList:

Private WithEvents _items As New BindingList(Of MenuItem)
Private _dataChanged As Boolean = False     ' maybe
AddHandler _items.ListChanged, AddressOf _listChanged

Public Property Items() As BindingList(Of MenuItem)
  Get
      Return itms
  End Get
  Set(value As List(Of MenuItem))
      _items = value
  End Set
End Property

'...

private Event _listChanged(ByVal sender As Object, _
          ByVal e As ListChangedEventArgs)
    _dataChanged = True
    RoutineToDoSomethingAboutDataChanged()
End Sub

您可以通过ListChangedEventArgs告知更改了哪个项目,这样您就可以根据需要对已更改的项目执行某些操作。 Me.Controls.AddRange(itms.ToArray())不会工作,因为BindingList不支持ToArray方法。

另外,将它们移动到ControlCollection是什么意思?这是序列化吗?