我們在定義一個新類的時候,這個類無法用現在的編輯器表達,我們需要自定義一個可以表達當前對象屬性的編輯器的時候,就需要使用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的預定義選擇。