我让一个自定义对象的这个属性显示在一个PropertyGrid中:
[DisplayName("Dirección IP Local")]
[Editor(typeof(Configuracion.Editors.IPAddressEditor), typeof(UITypeEditor))]
[Description("Dirección IP del computador en el cual está conectado el dispositivo.")]
public IPAddress IPLocal { get; set; }在同一个类的构造函数中,我有:
this.IPLocal = Common.Helper.ProgramInfo.GetLocalIPAddresses().FirstOrDefault();IPAddressEditor是这样的:
public class IPAddressEditor : UITypeEditor
{
private IWindowsFormsEditorService _editorService;
private IpAddressInput _ipAddressInput;
private bool _escKeyPressed;
public IPAddressEditor()
{
_ipAddressInput = new IpAddressInput();
_ipAddressInput.Width = 150;
_ipAddressInput.BackgroundStyle.BorderWidth = -1;
_ipAddressInput.ButtonClear.Visible = true;
_ipAddressInput.ValueChanged += _ipAddressInput_ValueChanged;
_ipAddressInput.PreviewKeyDown += _ipAddressInput_PreviewKeyDown;
}
void _ipAddressInput_PreviewKeyDown(object sender, System.Windows.Forms.PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Escape)
_escKeyPressed = true;
}
void _ipAddressInput_ValueChanged(object sender, EventArgs e)
{
if (_editorService != null)
_editorService.CloseDropDown();
}
public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context)
{
return UITypeEditorEditStyle.DropDown;
}
public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, IServiceProvider provider, object value)
{
if (provider != null)
{
_editorService =
provider.GetService(
typeof(IWindowsFormsEditorService))
as IWindowsFormsEditorService;
}
if (_editorService != null)
{
_escKeyPressed = false;
_editorService.DropDownControl(_ipAddressInput);
if (!_escKeyPressed)
{
IPAddress ip = IPAddress.None;
if (IPAddress.TryParse(_ipAddressInput.Value, out ip))
return ip;
}
}
return value;
}
}问题是编辑器内的控件(在本例中为_ipAddressInput)没有使用我在对象构造函数中分配的值进行初始化。
这是显而易见的,因为在类型编辑器构造函数中,我创建了一个新的IpAddressInput实例,所以问题是:初始化它的最佳方法是什么?
我在考虑为该变量创建一个公共设置器,并使用TypeDescriptor调用自定义对象的构造函数,但我认为这很棘手,
有没有更好的解决方案?
致敬詹姆
发布于 2018-03-09 23:02:38
最后,我找到了解决方案。
我刚添加了
_ipAddressInput.Text = value.ToString();在调用之前
_editorService.DropDownControl(_ipAddressInput);https://stackoverflow.com/questions/49184963
复制相似问题