2011-03-07 41 views
4

我在我的一個Silverlight 4.0頁面上遇到了一個非常奇怪的錯誤。我有一個窗體,它有一個默認禁用的「保存」按鈕。該表單由一系列用戶指定的缺省值填充,這些缺省值來自異步服務器調用(下面的MyFacade.getFormDefaults)。當用戶更改其中一個字段(填充後)時,我想要啓用「保存」按鈕。Silverlight 4.0表單初始化問題

我認爲我的邏輯是正確的,但我得到一個非常奇怪的錯誤,我無法找到很多有用的信息。錯誤是:System.InvalidOperationException: The initialization of an object or value resulted in an object or value being accessed recursively before it was fully initialized.

下面是什麼,我有一個非常簡單的版本...

profile.fs:

type profile() as this = 
    inherit UriUserControl("/whatever;component/profile.xaml", "profile") 

    [<DefaultValue>] 
    val mutable isFormLoaded : bool 
    [<DefaultValue>] 
    val mutable btnSave : Button 
    [<DefaultValue>] 
    val mutable txtEmail : TextBox 

    // constructor 
    do 
     this.isFormLoaded <- false 

     // make the "this" values point at the XAML fields 
     this.btnSave <- this?btnSave 
     this.txtEmail <- this?txtEmail 

     // get the form defaults and send them to 
     MyFacade.getFormDefaults(new Action<_>(this.populateFormDefaults)) 
     () 

    member this.populateFormDefaults (formDefaults : MyFormDefaultsUIVO array option) = 
     // populate this.txtEmail with the default value here 
     this.isFormLoaded <- true // set the form to be loaded once that's done 
     () 

    // enable the "Save" button when the user modifies a form field 
    member this.userModifiedForm (sender : obj) (args : EventArgs) = 
     // **** EXCEPTION OCCURS ON THE LINE BELOW **** 
     if this.isFormLoaded then 
      this.btnSave.IsEnabled <- true 
     () 

profile.xaml:

<nav:Page Name="profile" Loaded="formLoaded"> 
    <TextBox Name="txtEmail" TextChanged="userModifiedForm "/> 
    <Button Name="btnSave" IsEnabled="False"/> 
</nav:Page> 

即使我擺脫了所有的邏輯isFormLoaded,並簡單地設置this.btnSave.IsEnabled <- true裏面的this.userModifiedForm,我得到了同樣的錯誤。任何想法將不勝感激。謝謝。

回答

3

異常 - 在完全初始化之前訪問對象時,由F#運行時生成的「對象或值的初始化導致對象或值在其完全初始化之前被遞歸訪問」。

訪問this - 是否檢查isFormLoadedbtnSave.IsEnabled - 在構造函數運行之前會導致錯誤。您是否驗證過userModifiedForm僅在構造函數之後調用?

+0

我想其中一個XAML字段(如TextBox,ComboBox或CheckBox)正在觸發TextChanged或SelectionChanged事件並調用'userModifiedForm'。所以,是的,你是正確的......但我如何防止這種情況發生?令人討厭的是Silverlight將在表單完全構建之前觸發這些事件。 – 2011-03-07 18:09:44

+1

如果這是問題,最簡單的解決方案可能只是將'userModifiedForm'附加到構造函數末尾的'txtEmail'而不是xaml文件中。 – wmeyer 2011-03-07 18:11:29

+1

wmeyer的建議應該可行 - 在Silverlight的辯護中:既然它沒有與F#類型系統集成,我不知道它是如何自動避免導致這個問題的。 – 2011-03-07 18:14:41