Is it possible to supply a type converter for a static resource in WPF?
I have a newbie WPF question.
Imagine my user control has a namespace declaration like this:
xmlns:system="clr-namespace:System;assembly=mscorlib"
And I have resources for the user control like this:
<UserControl.Resources>
<system:Int32 x:Key="Today">32</system:Int32>
</UserControl.Resources>
And then somewhere in my user control I have this:
<TextBlock Text="{StaticResource Today}"/>
This will cause an error because Today
is defined as a integer resource, but the Text property is expecting a string. This example is contrived, but开发者_StackOverflow中文版 hopefully illustrates the question.
The question is, short of making my resource type exactly match the property type, is there a way for me to provide a converter for my resources? Something like IValueConverter for bindings or a type converter.
Thank you!
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;
}
}
精彩评论