1

我有一个嵌入 IronPython 以用作脚本语言的 WPF 应用程序。我有一个 IronPython 脚本可以用来做“事情”的对象模型。

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

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

map.CanvasLocation = 10,10

这会出现一个异常,即它无法从 PythonTuple 转换为 System.Windows.Point。

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

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

4

2 回答 2

2

我这样做的方法是使用 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));
}
于 2009-07-31T09:22:42.890 回答
0

为什么不做一个

map.CanvasLocation = Point(10,10)
于 2009-07-31T09:19:28.043 回答