开发者

how do I pass an argument to a class that inherits UITypeEditor

I have 开发者_StackOverflow中文版created an editor for a property. I would however like to pass some arguments to the constructor of the editor, but I am unsure as to how to do this.

FOO _foo = new foo();
[Editor(typeof(MyEditor), typeof(UITypeEditor))]
public object foo 
 {
 get { return _foo; }
 set {_foo = value;}
 }

~

class MyEditor: UITypeEditor
{
  public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, System.IServiceProvider provider, object value)
  {
    //some other code
    return obj;
  }
}


I know it's kinda old issue, but I've encountered similar problem and the only provided answer does not solve it a bit.

So I decided to write my own solution which is a little tricky and is more like a workaround, but it sure works for me, and maybe will help somebody.

Here's how it works. Since you don't create the instance of your own UITypeEditor derivative, you have no control over what arguments are passed to the constructor. What you can do, is to create another attribute and assign it to the same property, you are assigning your own UITypeEditor and pass your arguments to that attribute, and later read values from that attribute.

[Editor(typeof(MyEditor), typeof(UITypeEditor))]
[MyEditor.Arguments("Argument 1 value", "Argument 2 value")]
public object Foo { get; set; }

class MyEditor : UITypeEditor
{
    public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, System.IServiceProvider provider, object value)
    {
        string property1 = string.Empty, property2 = string.Empty;
        //Get attributes with your arguments. There should be one such attribute.
        var propertyAttributes = context.PropertyDescriptor.Attributes.OfType<ArgumentsAttribute>();
        if (propertyAttributes.Count() > 0)
        {
            var argumentsAttribute = propertyAttributes.First();
            property1 = argumentsAttribute.Property1;
            property2 = argumentsAttribute.Property2;
        }
        //Do something with your properties...
        return obj;
    }

    public class ArgumentsAttribute : Attribute
    {
        public string Property1 { get; private set; }
        public string Property2 { get; private set; }
        public ArgumentsAttribute(string prop1, string prop2)
        {
            Property1 = prop1;
            Property2 = prop2;
        }
    }
}


of course you can add another (parametrized) constructor to your myEditor class, something like this:

public class MyEditor: UITypeEditor
{
  // new parametrized constructor
  public MyEditor(string parameterOne, int parameterTwo...)
  {
    // here your code
  }

  ...
  ...
}

the problem is that you should also be in control of who calls that constructor because only then you can decide which constructor to use and you can specify/assign a value to the parameters.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜