PropertyGrid中如设置datetime类型字段,会自动使用DateTimePicker控件,但此DateTimePicker只能使用默认格式,无法输入时间。
使用PropertyGrid自定格式功能后,使用效果如下:
可以直接输入时间,或者点击下拉三角,调出 DateTimePicker控件选择时间
- 定义PropertyGrid控件绑定的对象
注意此处使用字符串类型,在MSSQL2008以上可以直接保存在time类型数据列中。
1234public class AppSettings{[Category("\t排程信息"), Editor(typeof(TimePickerEditor),typeof(UITypeEditor))]public string 开工时间 { get; set; }} - 自定义控件编辑UI
点击下拉三角后,出现DateTimePicker 控件,并设置此DateTimePicker CustomFormat = “HH:mm” 。
从PropertyGrid中取值,修改DateTimePicker值后更新回PropertyGrid。
1234567891011121314151617181920212223242526272829303132333435363738394041internal class TimePickerEditor : UITypeEditor{IWindowsFormsEditorService editorService;DateTimePicker picker = new DateTimePicker();public TimePickerEditor(){picker.Format = DateTimePickerFormat.Custom;picker.CustomFormat = "HH:mm";picker.ShowUpDown = true;}public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context){return UITypeEditorEditStyle.DropDown;//显示下拉按钮}public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, IServiceProvider provider, object value){string time;if (provider != null){this.editorService = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;}if (this.editorService != null){if (value == null){picker.Value = DateTime.Parse("00:00" as string);}else{time = value.ToString();picker.Value = DateTime.Parse(time);}this.editorService.DropDownControl(picker);value = picker.Value.ToString("HH:mm");}return value;}}
- 设置PropertyGrid值更新事件,检查输入的时间格式合法性,并自动转换
12345678910111213141516171819202122232425262728293031323334353637private void _mTaskGrid_PropertyValueChanged(object s, PropertyValueChangedEventArgs e){var value = e.ChangedItem.Value;var obj = (AppSettings)((PropertyGrid)s).SelectedObject;switch (e.ChangedItem.Label.ToString()){default: break;case "开工时间":try{var time = value.ToString().Substring(0, 5);obj.开工时间 = DateTime.Parse(time).ToString("HH:mm");}catch (Exception ex){DateTime dtDate;string time;if (value.ToString().Length < 2){time = ("00"+value.ToString()).Substring(value.ToString().Length) + ":00";}else {time = value.ToString().Substring(0,2) + ":00";}if (DateTime.TryParse(time, out dtDate)){obj.开工时间 = dtDate.ToString("HH:mm");}else{MessageBox.Show("时间格式不正确(HH: mm)");obj.开工时间 = "00:00";}}break;}}
参考资料:
https://stackoverflow.com/questions/4460489/choose-time-using-datetimepicker-in-propertygrid
https://blog.csdn.net/luyifeiniu/article/details/5426960
© 2018, ITJOY.NET. 版权所有. 如未注明,均为原创,转载请注明出处。