我有一个WPF应用程序,它嵌入了IronPython作为脚本语言。我有一个IronPython脚本可以用来做“东西”的对象模型。

然而,我遇到了一个奇怪的问题,我以一种我认为不正确的方式解决了这个问题。

在我的脚本中,我想输入以下内容来设置WPF中对象的位置。

map.CanvasLocation = 10,10

这是一个例外,说它无法从PythonTuple转换为System.Windows.Point。

我目前在c#对象中使用自定义类型转换器解决了这个问题,但我不确定这是否是最好的方法。

有没有办法告诉IronPython或.Net一般如何从一种类型转换为另一种可以在运行时扩展的类型?

有帮助吗?

解决方案

我这样做的方法是使用TypeDescriptor在运行时向PythonTuple添加类型转换器属性。

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

然后我使用以下代码在属性setter中找到转换器(SetMemberAfter方法)

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));
}

其他提示

为什么不做

map.CanvasLocation = Point(10,10)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top