在WPF中,是否可以为静态资源提供类型转换器?

12

我有一个新手WPF问题。

假设我的用户控件有以下命名空间声明:

xmlns:system="clr-namespace:System;assembly=mscorlib"

我有类似这样的用户控件资源:

<UserControl.Resources>
    <system:Int32 x:Key="Today">32</system:Int32>
</UserControl.Resources>

然后在我的用户控件中的某个地方,我有这样一个代码:

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

这会导致错误,因为Today被定义为一个整数资源,但是Text属性期望的是一个字符串。虽然这个例子有些牵强,但它能够阐述问题。

我的问题是,除了让我的资源类型与属性类型完全匹配之外,是否有一种方法可以为我的资源提供转换器?就像绑定的IValueConverter或类型转换器一样。

谢谢!

2个回答

24

如果使用绑定操作是可以实现的。虽然看起来有点奇怪,但这确实有效:

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

这是因为Binding引擎内置了基本类型的类型转换功能。此外,通过使用Binding,如果不存在内置转换器,您可以指定自己的转换器。


如果您想从一个Color类型的StaticResource中获取颜色组件(例如,更改StaticResource颜色的不透明度),该怎么办?执行以下操作似乎无效:<Color A="#99" R="{Binding Source={StaticResource PhoneAccentColor}, Path=R}" G="{Binding Source={StaticResource PhoneAccentColor}, Path=G}" B="{Binding Source={StaticResource PhoneAccentColor}, Path=B}"/> - Josh M.
1
它不起作用是因为你只能在DependencyObject的DependencyProperty上设置绑定。Color是一个结构体。你可以创建自己的颜色包装器对象,它是一个DepdendencyProperty,同时公开A,R,G,B和Color属性,这些属性本身就是DP。更改任何属性都会更新Color属性,更改它将更新所有其他属性。 - Abe Heidebrecht

4

Abe的答案在大多数情况下都有效。另一个选项是扩展StaticResourceExtension类:

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;
    }
}

哦!这也很有趣。谢谢Thomas! - Notre

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接