2011-04-04 51 views
0

我有我認爲我初始化一些成員的用戶控件:爲什麼我的UserControl不能保持其初始化?

// MyUserControl.cs 

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Drawing; 
using System.Data; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 

namespace MyNamespace 
{ 
    public partial class MyUserControl : UserControl 
    { 
     private string m_myString; 
     private int m_myInt; 

     public string MyString 
     { 
      get { return m_myString; } 
      set { m_myString = value; } 
     } 
     public int MyInt 
     { 
      get { return m_myInt; } 
      set { m_myInt = value; } 
     } 

     public MyUserControl() 
     { 
      InitializeComponent(); 

      MyString = ""; // was null, now I think it's "" 
      MyInt = 5;  // was 0, now I think it's 5 
     } 

     // ......... 
    } 
} 

當我插入這個控制到我的主要形式,雖然和調用內MyUserControl檢查值的功能,事情並不像他們正在初始化:

// MainForm.cs 

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 

namespace MyProgram 
{ 
    public partial class MainForm : Form 
    { 
     public MainForm() 
     { 
      InitializeComponent(); 
     } 

     private void MyButton_Click(object sender, EventArgs e) 
     { 
      // this prints 0 rather than 5 
      MessageBox.Show(this.theUserControl.MyInt.ToString()); 
     } 
    } 
} 

我猜這是一個真正簡單錯誤,但我不知道在哪裏。我已經嘗試過預先添加this.,但這可能不是固定代碼的方法。 :)

一如既往的感謝!

編輯: Pete建議您進入設計器代碼,告訴我寫入過程發生在哪裏。首先我調用用戶控件的構造函數,然後再用默認值覆蓋這些值。我沒有指定任何默認值(Sanjeevakumar Hiremath的建議),所以默認值是原始類型的默認值(對於int,這是0)。

+0

'私人字符串m_myInt控制這種行爲;',物業類型爲int。發佈編碼並重現問題的代碼。 – 2011-04-04 22:01:11

+1

你的設計器代碼是什麼樣的?你是否在你的UC構造函數代碼中設置了一個斷點,以查看什麼時候碰到和什麼時候出現? – 2011-04-04 22:02:08

+0

@Hans:對不起!我將變量名稱更改爲通用事物,並忘記改變它。 – John 2011-04-04 22:02:48

回答

3

你可能在這裏看到的是設計師的神器。如果您在添加MyUserControl之後在設計器中打開了MainForm,則可能在生成的InitializeComponent方法MainForm中記錄了默認值MyUserControl。這些記錄的值在MyUserControl的構造函數運行後被重新賦值,因此它們將覆蓋您設置的值。

您可以通過使用的DesignerSerializationVisibilityAttribute

+0

感謝您的回答。因此,DesignerSerializationVisibilityAttribute.Content具有僅爲設計器中看到的內容生成代碼的效果,而不是構造函數的組成部分。 – John 2011-04-04 23:42:42

2

使用[DefaultValue]屬性。它允許您在設計器中未指定值時指定控件屬性的默認值。

+0

謝謝你的回答。 – John 2011-04-04 23:38:01

相關問題