Silverlight 3自定义控件:只有'int'作为属性的数字类型? [例如。 long或int64好像破了]

时间:2010-05-07 09:22:46

标签: silverlight silverlight-3.0

我正在尝试将新属性添加到我的Silverlight 3自定义控件中。 int属性工作得很好,但是如果我将它更改为long或int64,我在运行时会遇到xaml解析器异常。

你知道这是SL3中的已知限制吗?

C#方面,新控制:

public class myExtTextBox : TextBox
{
    public int MaxNumericValue { get; set; }
    //public long MaxLongNumericValue { get; set; }  => This breaks the parser
}

XAML方:

<myExtTextBox x:Name="foobar"  MaxNumericValue="12" /> <!-- OK -->

<myExtTextBox x:Name="foobar"  MaxLongNumericValue="12" /> <!-- Breaks parser -->

1 个答案:

答案 0 :(得分:2)

在我看来,奇怪的是Xaml无法解析实现IConvertible的所有类型。 (我很想知道你们中任何一个MS潜伏者是否愿意接受教育的原因?)

这是一个可能有用的实现: -

public class ConvertibleTypeConverter<T> : TypeConverter where T: IConvertible
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        return sourceType.GetInterface("IConvertible", false) != null;
    }

    public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
    {
        return destinationType.GetInterface("IConvertible", false) != null;
    }

    public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
    {
        return ((IConvertible)value).ToType(typeof(T), culture);
    }

    public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
    {
        return ((IConvertible)value).ToType(destinationType, culture);
    }
}

现在在MaxLongNumericValue属性上,您使用如下属性: -

[TypeConverter(typeof(ConvertibleTypeConverter<long>))]
public long MaxLongNumericValue { get; set; }

现在,当Xaml解析器到达此属性时,它将遵循指定的TypeConverter