Search code examples
c#genericsuitypeeditor

Making a generic TypeEditor


Say I have a property Foo of type SomeType in a class of type SomeClass which is edited with a custom editor SomeTypeEditor:

[EditorAttribute(typeof(SomeTypeEditor), ...)]
public SomeType Foo
{
    get
    {
        return BuildFooFromInternalRepresenation();
    }
    set
    {
        UpdateInternalRepresentation(value);
    }
}

The SomeTypeEditor.EditValue function looks something like this:

public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, System.IServiceProvider provider, object value)
{
    IWindowsFormsEditorService edSvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
    if (null == edSvc)
    {
        return null;
    }
    var form = new SomeTypeEditorForm(value as SomeType);
    if (DialogResult.OK == edSvc.ShowDialog(form))
    {
        var someClass = context.Instance as SomeClass;
        someClass.Foo = form.Result;
        return someClass.Foo;
    }
    else
    {
        return value;
    }
}

I would now like to add another property Baz, also of type SomeType, to SomeClass. I would like to edit this property SomeTypeEditor but the line

someClass.Foo = form.Result;

in EditValue ties SomeTypeEditor to this particular property. It would be simple enough to just make a duplicate of SomeTypeEditor which edits Baz instead but I would like to avoid that if possible. Is there anyway to make my SomeTypeEditor generic (in any sense of the word) so it can be used to edit both Foo and Baz?


Solution

  • I just found out that if I let EditValue return a different object than value, set will be invoked on the property from which the edit originated, so just doing:

    if (DialogResult.OK == edSvc.ShowDialog(form))
    {
        var someClass = context.Instance as SomeClass;
        return form.Result;
    }
    

    works (SomeTypeEditor clones the incoming value and edits the clone).