PropertyGrid使用总结5 UITypeEditor

我们在定义一个新类的时候,这个类无法用现在的编辑器表达,我们需要自定义一个可以表达当前对象属性的编辑器的时候,就需要使用UITypeEditor。

我们定义一个坐标控件,基本定义如下:

代码呈现如下:

public partial class UserControl1 :Form

{

public double Value {

 

get;set;

}

public UserControl1()

{

InitializeComponent();

}

 

private void listBox1_SelectedValueChanged(object sender, EventArgs e)

{

Value = double.Parse(listBox1.SelectedItem.ToString());

this.Close();

}

}

 我们定义一个自定义的UITypeEditor对象实现对象的编辑

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Drawing.Design;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

using System.Windows.Forms.Design;

 

namespace AlbertControlExample.Controls

{

/// <summary>

/// 定义一个组件

/// </summary>

public class CustomDef : Component

{

public CustomDef()

{

Left = 0;

Top = 0;

}

public CustomDef(int left, int top)

{

this.Left = left;

this.Top = top;

}

[Editor(typeof(CustomDefEditor), typeof(UITypeEditor))]

public double Left { get; set; }

public double Top { get; set; }

 

 

}

 

public class CustomDefEditor : UITypeEditor

{

 

public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)

{

return UITypeEditorEditStyle.Modal;

}

public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)

{

IWindowsFormsEditorService editorService = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));

UserControl1 userControl = new UserControl1();

editorService.ShowDialog(userControl);

if (value.GetType() == typeof(double))
{

return userControl.Value;

}

editorService.CloseDropDown();

return userControl.Value;

}
 
}

}

根据以上的代码,实现了一个属性的自定义编辑器,其显示效果如下:

实现了对Left属性的一个编辑器,当前编辑器是一个对话框,实现Left的预定义选择。

猜你喜欢

转载自www.cnblogs.com/minhost/p/12301286.html