Skip to main content
 首页 » 编程设计

c#之如何创建将字符串限制为 n 个字符的 PropertyGrid 编辑器

2024年02月23日26wuhuacong

我试图创建自己的 UITypeEditor,但 EditValue 方法从未被调用

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; 
    } 
 
} 

这样使用:

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

这里我尝试将字符串限制为 3 个字符,如果可以通过属性定义会更好。

请您参考如下方法:

由于您希望在属性下方的下拉区域中显示文本框,因此请更改您的 GetEditStyle 实现以返回 UITypeEditorEditStyle.DropDown 而不是 UITypeEditorEditStyle .无。

这将在属性旁边显示一个下拉箭头,就像您在 ComboBox 上看到的那样,单击箭头然后将调用您的 EditValue 方法以显示一个下拉文本框以编辑属性(property)值(value)。