我正在尝试添加一个日历,例如选择月份和年份的自定义用户控件。在用户控制代码中,我将两个属性Month和Year设置为当前月份和年份。
public MonthPicker()
{
InitializeComponent();
m_MonthLabels = new Label[]
{
lblJanuary,
lblFebruary,
lblMarch,
lblApril,
lblMay,
lblJune,
lblJuly,
lblAugust,
lblSeptember,
lblOctober,
lblNovember,
lblDecember
};
m_NotSelected = new Font("Sans Serif", 8.25F, FontStyle.Regular);
m_Selected = new Font("Sans Serif", 8.25F, FontStyle.Bold);
Month = DateTime.Now.Month;
Year = DateTime.Now.Year;
lblYear.Text = Year.ToString();
groupBox2.Visible = false;
groupBox1.Height = 20;
CalendarIsDisplayed = false;
CalendarIsNotChanged = false;
SetMonthLabelSelected(Month);
}
但是,当我将其包含在我的应用程序表单中时,设计器会获取月份和年份的硬编码值。因此,当月份发生变化时,它仍会显示我的月份。
// tsMonthPicker
//
this.tsMonthPicker.BackColor = System.Drawing.SystemColors.Control;
this.tsMonthPicker.CalendarIsDisplayed = false;
this.tsMonthPicker.CalendarIsNotChanged = false;
this.tsMonthPicker.Location = new System.Drawing.Point(104, 14);
this.tsMonthPicker.Margin = new System.Windows.Forms.Padding(0);
this.tsMonthPicker.Month = 1;
this.tsMonthPicker.Name = "tsMonthPicker";
this.tsMonthPicker.Size = new System.Drawing.Size(215, 20);
this.tsMonthPicker.TabIndex = 6;
this.tsMonthPicker.Value = new System.DateTime(2017, 1, 1, 0, 0, 0, 0);
this.tsMonthPicker.Year = 2017;
this.tsMonthPicker.Change += new Time_and_Billing_System.MonthPicker.MonthPickerChangeHandler(this.tsMonthPicker_Changed);
this.tsMonthPicker.Load += new System.EventHandler(this.tsMonthPicker_Load);
如何更改用户控件中的代码,以便表单设计器文件自动执行 -
this.tsMonthPicker.Month = System.DateTime.Now.Month;
this.tsMonthPicker.Year = System.DateTime.Now.Year;
答案 0 :(得分:0)
将这两行放在Form_Load方法中,用于嵌入此MonthPicker的表单。
private void Form1_Load(object sender, EventArgs e)
{
this.tsMonthPicker.Month = System.DateTime.Now.Month;
this.tsMonthPicker.Year = System.DateTime.Now.Year;
}
在对象查看器中,选择Form对象时,选择Events视图(Lightning Bolt),在列表中找到Load,双击该空格,此方法将出现在代码中。
答案 1 :(得分:0)
您可以使用DesignMode
属性。如果每次启动应用程序时都需要默认值Now,则不要说明。如果是这种情况,那么您就不需要DesignMode。
public MonthPicker()
{
if (this.DesignMode)
{
//These values are only set when the control is created in design mode
this.tsMonthPicker.Month = System.DateTime.Now.Month;
this.tsMonthPicker.Year = System.DateTime.Now.Year;
}
}