如何创建将字符串限制为 n 个字符的 PropertyGrid 编辑器
我尝试创建自己的 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 个字符,如果可以通过属性定义,那就更好了。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您希望在属性下方的下拉区域中显示文本框,因此请将
GetEditStyle
的实现更改为返回UITypeEditorEditStyle.DropDown
而不是UITypeEditorEditStyle.None< /代码>。
这将在属性旁边显示一个下拉箭头,就像您在组合框中看到的那样,单击该箭头将调用您的
EditValue
方法以显示一个下拉文本框以编辑属性值。Since you want to show a TextBox in a drop-down area beneath the property, change your implementation of
GetEditStyle
to returnUITypeEditorEditStyle.DropDown
instead ofUITypeEditorEditStyle.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.