2016-01-26 50 views
-1

Gyzz我试图用只读列表(Of Points)属性创建一个用户控件。我在初始化和使用该属性时遇到问题!帮助我,我对视觉基础很陌生。使用只读列表属性

的UserControl1:

Public Class PointEntryPanel 

Dim P as List(of PointF) = New List(Of PointF) 
Public ReadOnly Property Points as List(Of PointF) 
    Get 
     P = Points 
     return P 
    End Get 
End Property 

End Class 

形式:

Public Class Form1 

Private Sub Form1_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseDoubleClick 


    ListBox1.Items.Add("You see ,No null reference exceptions") 
    ListBox1.Items.Add("I want a property just like this") 
    PointEntryPanel1.Points.Add(New PointF(0, 0)) 'While this creates exceptions 
    PointEntryPanel1.Points.Add(New PointF(1, 1)) 'And the point is not added to the PList 
    MessageBox.Show(PointEntryPanel1.PArray.ToString) 'this shows an empty box 

End Sub 

End Class 

我想就像在列表框控件的 '商品' 属性的代码属性

+0

是'PointEntryPanel1'中应该是'UserControl1'第二块是'PArray'应该正在使用“点数”?它如何不符合Magnus的答案? – Plutonix

+0

是的,谢谢你通知它,这是一个错误!我得到一个空引用异常,并且这些点没有被“Points.Add”方法添加! –

+0

'Dim P as List(of PointF)= New List(Of Points)'不会编译。如果你解决了这个问题,只是在返回中返回P,那么它就会正常工作 – Plutonix

回答

1

你必须实例P和然后归还物业

Private p As New List(of PointF) 
Public ReadOnly Property Points as List(Of PointF) 
    Get 
     return p 
    End Get 
End Property 
+0

抱歉,我忘了在写这篇文章时插入新的关键字!但是我得到了“P = Points”的空引用豁免,并且没有在“PointEntryPanel1.PArray.Add(New PointF(0,0))”上添加到PArray中!这是我的问题 –

+0

跳过'P = Points'并返回'P' – Magnus

+0

仍然'PointEntryPanel1.PArray.Add(New PointF(0,0))'不起任何作用!我需要该行来更改UserControl1中的'P'列表! –

0

您必须实例化新列表(T)。 使用“新”来做到这一点。

例如:

Private Points As New List(Of Point) 'instantiate the List(of T) 


Public ReadOnly Property AllPoints As List(Of Point) 
    Get 
     Return Points 
    End Get 
End Property 

你可以做这样的事情还有:

Public ReadOnly Property GetAllPoints As List(Of String) 
    Get 
     Return Points 
    End Get 
End Property 
'property only to return the List (for instance visible to 
'users if you want to create a classlibrary.) 



Private Property AllPoints As List(Of String) 
    Set(value As List(Of String)) 
     If (Points.Equals(value)) Then Exit Property 
     Points.Clear() 
     Points.AddRange(value.ToArray) 
    End Set 
    Get 
     Return Points 
    End Get 'return the points 
End Property 
'Property to set and get the list (not visible in a classlibrary because it 
is private) 
'this can be used in the class you have pasted it only. 
+0

我想要这个PArray属性就像列表框控件中的'Items'属性一样!我可以向用户控件添加单独的方法存根,以添加,删除和操作P中的项目,但它使我的工作复杂化了!这样会更容易,对! –