How to create a PropertyGrid editor that limits a string to n characters

好久不见. 提交于 2019-12-11 05:06:29

问题


I have attempted to create my own UITypeEditor but the EditValue method never gets called

public class BoundedTextEditor : UITypeEditor
{

    public override System.Drawing.Design.UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context)
    {
        return UITypeEditorEditStyle.None;
    }

    public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, System.IServiceProvider provider, object value)
    {
        if (value.GetType() != typeof(string)) return value;
        var editorService = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
        if (editorService != null)
        {
            var textBox = new TextBox { Text = value.ToString(), Size = new Size(200, 100), MaxLength = 3 };
            editorService.DropDownControl(textBox);
            return textBox.Text;
        }
        return value;
    }

}

Used like this:

[Editor(typeof(BoundedTextEditor), typeof(UITypeEditor))]
public string KeyTip
{
    get
    {
        return _keyTip;
    }
    set
    {
        _keyTip = value;
    }
}

Here I have attempted to limit the string to 3 characters, would be better if that can be defined via an attribute.


回答1:


Since you want to show a TextBox in a drop-down area beneath the property, change your implementation of GetEditStyle to return UITypeEditorEditStyle.DropDown instead of UITypeEditorEditStyle.None.

This will show a drop-down arrow next to the property like you see on a ComboBox, clicking on the arrow will then call your EditValue method to show a drop-down text box to edit the property value.



来源:https://stackoverflow.com/questions/7014021/how-to-create-a-propertygrid-editor-that-limits-a-string-to-n-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!