Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override PropertyDescriptor.GetValue and PropertyDescriptor.SetValue for dynamic object in .NET 4

We are using DynamicObject for dynamic properties creation, but then we want to use PropertyGrid to show this properties and edit them.

Firstly, I found this article, and this one. I try to use second article code, but in more generic fashion, basically to replace all methods names constants with variables. But the problem is that VS2010 can't find CSharpGetMemberBinder type.

Does someone know how to replace it? or what is the best approach?

like image 595
Jevgenij Nekrasov Avatar asked Nov 05 '22 07:11

Jevgenij Nekrasov


2 Answers

You can use the open source framework Dynamitey it lets you invoke dynamic properties of any IDynamicMetaObjectProvider by string name.

    public override object GetValue(object component)
    {
        return Dyanmic.InvokeGet(component,propertyName);
    }

    public override void SetValue(object component, object value)
    {
         Dyanmic.InvokeSet(component,propertyName, value);
    }
like image 45
jbtule Avatar answered Nov 09 '22 10:11

jbtule


Instead of using that article's Helper class (which is outdated), you can simply cast to IDictionary and set / retrieve the values:

        public override object GetValue(object component)
        {
            if (_owner != component) throw new InvalidOperationException("GetValue can only be used with the descriptor's owner.");
            //return DynamicHelper.GetValue(component, _propertyName);
            return ((IDictionary<String, object>)component)[_propertyName];
        }

        public override void SetValue(object component, object value)
        {
            if (_owner != component) throw new InvalidOperationException("SetValue can only be used with the descriptor's owner.");
            OnValueChanged(component, EventArgs.Empty);
            //DynamicHelper.SetValue(component, _propertyName, value);
            ((IDictionary<String, object>)component)[_propertyName] = value;
        }

Edit: This may only work in the case of ExpandoObjects, which was what the article was using.. if you created your own dynamic class with a different backing, you may need to change this.

like image 149
Andrew Hanlon Avatar answered Nov 09 '22 10:11

Andrew Hanlon