Joh*_*son 5 c# wpf xaml typeconverter markup-extensions
我正在尝试写一个像这样的markupextension:
[MarkupExtensionReturnType(typeof(Length))]
public class LengthExtension : MarkupExtension
{
// adding the attribute like this compiles but does nothing.
public LengthExtension([TypeConverter(typeof(LengthTypeConverter))]Length value)
{
this.Value = value;
}
[ConstructorArgument("value")]
public Length Value { get; set; }
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this.Value;
}
}
Run Code Online (Sandbox Code Playgroud)
要像这样使用:
<Label Content="{units:Length 1 mm}" />
Run Code Online (Sandbox Code Playgroud)
Errs:
类型"长度"的TypeConverter不支持从字符串转换.
如果我:TypeConverter工作:
Value房产上并有一个默认的ctor.Length用属性装饰类型.虽然这可能是x/y,但我不想要任何这些解决方案.
这是转换器的代码:
public class LengthTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(InstanceDescriptor) || destinationType == typeof(string))
{
return true;
}
return base.CanConvertTo(context, destinationType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
var text = value as string;
if (text != null)
{
return Length.Parse(text, culture);
}
return base.ConvertFrom(context, culture, value);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (value is Length && destinationType != null)
{
var length = (Length)value;
if (destinationType == typeof(string))
{
return length.ToString(culture);
}
else if (destinationType == typeof(InstanceDescriptor))
{
var factoryMethod = typeof(Length).GetMethod(nameof(Length.FromMetres), BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(double) }, null);
if (factoryMethod != null)
{
var args = new object[] { length.metres };
return new InstanceDescriptor(factoryMethod, args);
}
}
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
Run Code Online (Sandbox Code Playgroud)
来自MSDN,应用 TypeConverterAttribute(重点是我的):
为了让 XAML 处理器将自定义类型转换器用作自定义类的代理类型转换器,您必须将 .NET Framework 属性 TypeConverterAttribute 应用到您的类定义...
和
您还可以为每个属性提供类型转换器。不要将 .NET Framework 属性 TypeConverterAttribute 应用于类定义,而是将其应用于属性定义...
没有提到应用该属性的任何其他地方。所以你的问题的答案很有可能
不可以,TypeConverter 不能用于构造函数参数。