4

I define a property for my properygrid that value of it is collection of creators. I define CreatorsEditor class. In this class , I use HumanRolesCode variable. How can I access to this variable in attribute of property for set value. I want change HumanRolesCode value. for example : [Editor(typeof(CreatorsEditor(HumanRolesCode = 10))]

my codes is :

[Editor(typeof(CreatorsEditor), typeof(UITypeEditor))]
public string Creators { get; set; }
//-------------------------------------

public class CreatorsEditor : UITypeEditor
{
    public static int HumanRolesCode;

    public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
    {
        return UITypeEditorEditStyle.Modal;
    }

    public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
    {
        IWindowsFormsEditorService svc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
        if (svc != null)
        {
            CreatorFrm.HumanRoleCode = HumanRolesCode;
            CreatorFrm Frm = new CreatorFrm();
            if (svc.ShowDialog(Frm) == System.Windows.Forms.DialogResult.OK)
            {
                string HumanNames = "";
                for (int i = 0; i < Frm.DgvCreator.Rows.Count; i++)
                    if (Boolean.Parse(Frm.DgvCreator[0, i].Value.ToString()) == true)
                        HumanNames += Frm.DgvCreator[2, i].Value.ToString() + " , ";
                if (!string.IsNullOrEmpty(HumanNames))
                    HumanNames = HumanNames.Substring(0, HumanNames.Length - 3);
                return HumanNames;
            }
        }
        return value;
    }
}
Ali Ahmadi
  • 2,387
  • 4
  • 31
  • 48

1 Answers1

2

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type.

It seems to be impossible to assign some value, and generally make some run-time code (method \ property) to be executed by the declaration of custom attribute.

Custom attributes are just a way to associate additional information with a target, the compiler just adds additional information into the metadata... While you want to change at compile time, a variable that exists just at run-time.

Furthermore, custom attribute's instance is not created, until you use a reflection to retrieve it (again - at run-time, while the declaration was at compile-time).

There is a chapter about custom attributes in Jeffrey Richter's book "CLR via C#". I recommend you to read it to understand how custom attributes behave, what is possible to do using them and how to use them.

Vitali Kaspler
  • 1,340
  • 10
  • 16