1

I've got a WPF application that embeds IronPython to use as a scripting language. I've got an object model that IronPython scripts can use to do 'stuff'.

However I've come across a strange problem that I've solved in a way that I don't believe is correct.

In my script I want to type the following to set the location of an object in WPF.

map.CanvasLocation = 10,10

This comes up with an exception saying that it cannot convert from PythonTuple to System.Windows.Point.

I've currently solved that using a custom type converter in my c# object, but I'm not sure if this is the best way to do it.

Is there a way to tell IronPython or .Net in general how to convert from one type to another that can be extended at run time?

2 Answers 2

2

The way I do this is to use TypeDescriptor to add a type converter attribute to PythonTuple at runtime.

TypeDescriptor.AddAttributes(typeof(PythonTuple), 
    new TypeConverterAttribute(typeof(Converter)));

Then I use the following code to find the converter in the attribute setter (SetMemberAfter method)

var converter = TypeDescriptor.GetConverter(value);
if (converter.CanConvertTo(destinationType))
{
    var destinationValue = converter.ConvertTo(value, destinationType);
    return destinationValue;
}
else
{
    throw new InvalidOperationException("Cannot convert from {0} to {1}".UIFormat(
        value == null ? "null" : value.GetType().Name, destinationType.Name));
}
Sign up to request clarification or add additional context in comments.

Comments

0

Why not do a

map.CanvasLocation = Point(10,10)

1 Comment

I could do. This would work, but it is also not very user friendly. I want to make the scripts as easy to use as possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.