由于WinForm自带的DateTimePicker不能设置空值(Null),所以我基于原来的DateTimePicker做了扩展。
若有bug,可反馈,我再修改。
namespace WinFormTest
{
public class DateTimePicker2 : DateTimePicker
{
const string NullableFormat = " ";
bool isSelfSetting;
string originalCustomFormat;
bool originalCustomFormatInitialized;
DateTimePickerFormat? originalFormat;
bool IsNullableState
{
get { return Format == DateTimePickerFormat.Custom && CustomFormat == NullableFormat; }
}
void SetNullable(bool nullable)
{
if (!this.originalFormat.HasValue)
{
this.originalFormat = Format;
}
if (!this.originalCustomFormatInitialized)
{
this.originalCustomFormat = CustomFormat;
this.originalCustomFormatInitialized = true;
}
if (!Nullable) return;
this.isSelfSetting = true;
Format = nullable ? DateTimePickerFormat.Custom : this.originalFormat.Value;
CustomFormat = nullable ? NullableFormat : this.originalCustomFormat;
this.isSelfSetting = false;
}
#region Properties
public bool Nullable { get; set; }
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new DateTime? Value
{
get { return IsNullableState ? (DateTime?)null : base.Value; }
set
{
if (value.HasValue)
base.Value = value.Value;
SetNullable(!value.HasValue);
}
}
public new DateTimePickerFormat Format
{
get { return base.Format; }
set
{
if (!this.isSelfSetting)
this.originalFormat = value;
base.Format = value;
}
}
public new string CustomFormat
{
get { return base.CustomFormat; }
set
{
if (!this.isSelfSetting)
{
this.originalCustomFormat = value;
this.originalCustomFormatInitialized = true;
}
base.CustomFormat = value;
}
}
#endregion
#region Events
protected override void OnGotFocus(EventArgs e)
{
if (IsNullableState)
SetNullable(false);
base.OnGotFocus(e);
}
protected override void OnMouseDown(MouseEventArgs e)
{
if (IsNullableState)
SetNullable(false);
base.OnMouseDown(e);
}
protected override void OnKeyDown(KeyEventArgs e)
{
SetNullable(e.KeyCode == Keys.Back || e.KeyCode == Keys.Delete);
base.OnKeyDown(e);
}
#endregion
}
}