如果你经常使用DateTimePicker
像这样的对象,你可以创建两个小的自定义类:aStartDateTimePicker
和 an EndDateTimePicker
。每个类都将派生自DateTimePicker
,并且仅在OnValueChanged事件上有一个布尔值和一个 EventHandler。该事件将用于在设置后调整值,而布尔值将用于实现Balking Pattern。这是一个示例StartDateTimePicker
:
public class StartDateTimePicker : DateTimePicker
{
bool handling = false;
// Note:
public StartDateTimePicker()
: base()
{
// This could be simplified to a lambda expression
this.ValueChanged += new EventHandler(StartDateTimePicker_ValueChanged);
}
void StartDateTimePicker_ValueChanged(object sender, EventArgs e)
{
// If the value is being changed by this event, don't change it again
if (handling)
{
return;
}
try
{
handling = true;
// Add your DateTime adjustment logic here:
Value = Value.Date;
}
finally
{
handling = false;
}
}
}
然后,您只需使用这些来代替您的普通DateTimePicker
对象,您就不必再担心确保日期被适当地调整了。
It would cost you the time to write the EndDateTimePicker
class (the above is already a fully functional StartDateTimePicker
), but it would make things easier down the road as you use these in more places.