2010-05-18 64 views
0

我已經定義了控制:F#的Silverlight 3.0自定義控件屬性拋出:NullReferenceException異常

static member ItemsProperty : DependencyProperty = 
     DependencyProperty.Register(
      "Items", 
      typeof<MyMenuItemCollection>, 
      typeof<MyMenu>, 
      null); 

member this.Items 
     with get() : MyMenuItemCollection = this.GetValue(MyMenu.ItemsProperty) :?> MyMenuItemCollection 
     and set (value: MyMenuItemCollection) = this.SetValue(MyMenu.ItemsProperty, value); 

的問題發生在訪問:

for menuItem in this.Items do 
    let contentElement: FrameworkElement = menuItem.Content 

在那裏我得到空引用異常在這個.Items;

'商品' 扔類型的異常 'System.NullReferenceException'

後不久我在構造函數初始化:

do 
    this.Items <- new CoolMenuItemCollection() 
+0

嗨,這不是一個討論的論壇之多的問題和答案的地方。假設任何人查看你的帖子沒有閱讀你的「以前的帖子」 – 2010-05-18 18:28:43

+0

夠真實 - 犯了大聲打字。以前的帖子是完全無關緊要的。 – akaphenom 2010-05-18 18:31:54

回答

1

我認爲問題在於F#中的static member與公共字段不符合您的預期,而是與get成員的屬性相對應。這意味着,每次你訪問this.ItemsProperty時,你實際上正在創建一個新的依賴屬性。

您可以創建這樣一個靜態字段:

type Control = 
    // private static field 
    static let itemsProperty : DependencyProperty = 
    DependencyProperty.Register 
     ("Items", typeof<MyMenuItemCollection>, typeof<MyMenu>, null); 
    // public static property with getter 
    static member ItemsProperty = itemsProperty 

    // You can use both private 'itemsProperty' field or public property here 
    member this.Items 
    with get() : MyMenuItemCollection = 
     this.GetValue(itemsProperty) :?> MyMenuItemCollection 
    and set (value: MyMenuItemCollection) = 
     this.SetValue(itemsProperty, value) 
+0

它修復了NullReference異常。我想我需要更多地研究F#中的靜態修飾符;控制仍然不是渲染輸出 - 但我正在向前邁進。謝謝 – akaphenom 2010-05-18 19:51:02

0

的CLR吸氣不被大多數的所謂該框架。這是爲了開發人員訪問的便利是代碼隱藏在文件後面。

如果您需要,您的構造函數將是初始化集合的好地方。

不要將一個默認值(在上面的依賴項屬性聲明中爲null)設置爲一個空集合。默認值是一個共享的單個靜態實例 - 因此控件的每個實例都將共享同一個列表,而不是您想要的。

+0

謝謝;通過在100%F#中編寫silverlight應用程序,我對.NET自我熟悉。它證明是一個比預期更大的項目。 DependencyProperty.Register在MSDN上顯示兩個簽名 - 但是我的智能感知只顯示一個簽名,需要四個參數。我錯過了什麼嗎?或者可能是F#混合sigs? – akaphenom 2010-05-18 18:41:39

+0

這應該不重要 - 您的依賴屬性Register語句已經是正確的。 – 2010-05-18 18:45:30

+0

這就是我最初的想法,但我有問題,因爲所述的代碼是拋出NullReference異常...所以我認爲必須關閉 – akaphenom 2010-05-18 18:54:06

相關問題