Is it possible to supply a type converter for a static resource in WPF?

帅比萌擦擦* 提交于 2019-11-30 12:23:43

It is possible if you use a Binding. It seems a little weird, but this will actually work:

<TextBlock Text="{Binding Source={StaticResource Today}}" />

It is because the Binding engine has built-in type conversion for the basic types. Also, by using the Binding, if a built-in converter doesn't exist, you can specify your own.

Abe's answer should work in most situations. Another option would be to extend the StaticResourceExtension class :

public class MyStaticResourceExtension : StaticResourceExtension
{
    public IValueConverter Converter { get; set; }
    public object ConverterParameter { get; set; }

    public MyStaticResourceExtension()
    {
    }

    public MyStaticResourceExtension(object resourceKey)
        : base(resourceKey)
    {
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        object value = base.ProvideValue(serviceProvider);
        if (Converter != null)
        {
            Type targetType = typeof(object);
            IProvideValueTarget target = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
            if (target != null)
            {
                DependencyProperty dp = target.TargetProperty as DependencyProperty;
                if (dp != null)
                {
                    targetType = dp.PropertyType;
                }
                else
                {
                    PropertyInfo pi = target.TargetProperty as PropertyInfo;
                    if (pi != null)
                    {
                        targetType = pi.PropertyType;
                    }
                }
            }
            value = Converter.Convert(value, targetType, ConverterParameter, CultureInfo.CurrentCulture);
        }
        return value;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!