我正在尝试使用propertygrid
和datetimepicker
选择一个时间(小时和分钟)。
我创建了自己的编辑器
麻烦的是它没有显示文本中的值,值也可以有日历:
这里有代码:
public class Tests
{
private DateTimePicker time = new DateTimePicker();
[Editor(typeof(MyEditor), typeof(UITypeEditor))]
public DateTimePicker Time
{
get { return time; }
set { time = value; }
}
public Tests()
{
time.Format = DateTimePickerFormat.Time;
time.CustomFormat = "hh:mm";
time.Value = DateTime.Now;
DateTime t = new DateTime();
}
}
class MyEditor : UITypeEditor
{
IWindowsFormsEditorService editorService;
DateTimePicker picker = new DateTimePicker();
public MyEditor()
{
picker.Format = DateTimePickerFormat.Custom;
picker.CustomFormat = "hh:mm";
picker.ShowUpDown = true;
picker.ValueChanged += new EventHandler(picker_ValueChanged);
}
void picker_ValueChanged(object sender, EventArgs e)
{
this.editorService.CloseDropDown();
}
public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, IServiceProvider provider, object value)
{
if (provider != null)
{
this.editorService = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;
}
if (this.editorService != null)
{
DateTimePicker tmp = (DateTimePicker)value;
tmp.CustomFormat = "hh:mm";
tmp.Text = tmp.Value.ToString();
picker = tmp;
this.editorService.DropDownControl(picker);
}
return value;
}
public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context)
{
return UITypeEditorEditStyle.DropDown;
}
}
答案 0 :(得分:4)
我终于通过使用字符串
来做到了public class Tests {
private string time;
[Editor(typeof(TimePickerEditor), typeof(UITypeEditor))]
public string Time {
get { return time; }
set { time = value; }
}
internal class TimePickerEditor : UITypeEditor {
IWindowsFormsEditorService editorService;
DateTimePicker picker = new DateTimePicker();
string time;
public TimePickerEditor() {
picker.Format = DateTimePickerFormat.Custom;
picker.CustomFormat = "mm:HH";
picker.ShowUpDown = true;
}
public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, IServiceProvider provider, object value) {
if (provider != null) {
this.editorService = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;
}
if (this.editorService != null) {
if (value == null) {
time = DateTime.Now.ToString("HH:mm");
}
this.editorService.DropDownControl(picker);
value = picker.Value.ToString("HH:mm");
}
return value;
}
public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context) {
return UITypeEditorEditStyle.DropDown;
}
}
}
答案 1 :(得分:1)
您需要实现一个System.ComponentModel.TypeConverter
,它在您的对象和字符串之间进行转换,而不是使用字符串本身。 PropertyGrid
内部使用TypeConverter
类......虽然不是很明显:)