我为一个属性创建了一个编辑器。但是,我希望将一些参数传递给编辑器的构造函数,但我不确定如何做到这一点。
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;
}
}发布于 2011-09-18 02:04:17
当然,您可以向myEditor类添加另一个(参数化的)构造函数,如下所示:
public class MyEditor: UITypeEditor
{
// new parametrized constructor
public MyEditor(string parameterOne, int parameterTwo...)
{
// here your code
}
...
...
}问题是,您还应该控制谁调用该构造函数,因为只有这样,您才能决定使用哪个构造函数,并且可以为参数指定/赋值。
发布于 2015-03-24 18:49:01
我知道这是一个老问题,但我遇到过类似的问题,唯一提供的答案并没有解决它。
因此,我决定编写自己的解决方案,这有点棘手,更像是一种变通办法,但它对我来说肯定有效,也许会对某些人有所帮助。
下面是它的工作原理。由于您不创建自己的UITypeEditor派生的实例,因此无法控制将哪些参数传递给构造函数。您可以做的是创建另一个属性并将其分配给相同的属性,您将分配自己的UITypeEditor并将参数传递给该属性,然后从该属性中读取值。
[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;
}
}
}https://stackoverflow.com/questions/7456738
复制相似问题