2016-01-26 94 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中的項目,但它使我的工作複雜化了!這樣會更容易,對! –