为什么我的UserControl不能保持初始化?

时间:2011-04-04 21:57:17

标签: c# user-controls initialization

我有一个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)。

2 个答案:

答案 0 :(得分:3)

你在这里看到的是设计师的神器。如果您在添加MainForm后在设计器中打开MyUserControl,则可能会在生成的MyUserControl InitializeComponent方法中记录默认值MainForm。在MyUserControl的构造函数运行后,这些记录的值会重新分配,因此它们会覆盖您设置的值。

您可以使用DesignerSerializationVisibilityAttribute

来控制此行为

答案 1 :(得分:2)

使用[DefaultValue]属性。它允许您在设计器中未指定值时为控件的属性指定默认值。

相关问题