Lance
Lance

Reputation: 261

WPF c# DynamicObject. how to enforce type checking on the added properties?

I define a DynamicObject.

I have created a list of DynamicObjects with the same structure and link them to a WPF GridView.

I allow editing of some of the properties via the grid.

As the DynamicObjects present the property data as objects, how can I enforce Type restrictions?

if the user types alphabet into a cell that I would like as an int how can I get the DynamicObject to refuse the input?

Upvotes: 0

Views: 67

Answers (2)

Lance
Lance

Reputation: 261

In the constructor of my DynamicObject, I pass in with the properties definition, a dictionary of the types.

I then override the TrySetMember method to convert the value from the string supplied by the grid into its required type.

The issue I now have is sending a error message back to the grid if the conversion fails.

Here is My DynamicObject definition:

public sealed class FwDynamicObject : DynamicObject
{
    private readonly Dictionary<string, object> _properties;
    private readonly Dictionary<string, Type> _propertyTypes;

    public FwDynamicObject(Dictionary<string, object> properties, Dictionary<string, Type> propertyTypes = null)
    {
        _properties = properties;
        _propertyTypes = propertyTypes;
    }

    public override IEnumerable<string> GetDynamicMemberNames()
    {
        return _properties.Keys;
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        if (_properties.ContainsKey(binder.Name))
        {
            result = _properties[binder.Name];
            return true;
        }
        else
        {
            result = null;
            return false;
        }
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        if (_properties.ContainsKey(binder.Name))
        {
            var t = GetMemberType(binder.Name);
            if (t != null)
            {
                try
                {
                    value = Convert.ChangeType(value, t);
                }
                catch(Exception e)
                {
                    return false;
                }
            }

            _properties[binder.Name] = value;
            return true;
        }
        else
        {
            return false;
        }
    }

    private Type GetMemberType(string name)
    {
        if (_propertyTypes.ContainsKey(name))
        {
            return _propertyTypes[name];
        }
        return null;
    }
}

Upvotes: 0

RyanHx
RyanHx

Reputation: 421

You could use a TryParse wherever you're taking the cell input:

int result;
if(int.TryParse(cellText, out result))
{
   // Is an integer              
}
else
{

}

bool and other value types also have a TryParse if you're taking those values as well.

See also:

Upvotes: 1

Related Questions