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 之类的东西。

谢谢!

4

2 回答 2

24

如果您使用绑定是可能的。这似乎有点奇怪,但这实际上会起作用:

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

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

于 2010-03-04T19:47:32.337 回答
4

安倍的回答应该适用于大多数情况。另一种选择是扩展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;
    }
}
于 2010-03-04T19:56:22.180 回答