代码之家  ›  专栏  ›  技术社区  ›  Notre

是否可以为wpf中的静态资源提供类型转换器?

  •  11
  • Notre  · 技术社区  · 15 年前

    我有个新的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 定义为整数资源,但文本属性应为字符串。这个例子是人为的,但希望能说明这个问题。

    问题是,除了使资源类型与属性类型完全匹配之外,是否有方法为资源提供转换器?类似于用于绑定的ivalueconverter或类型转换器。

    谢谢您!

    2 回复  |  直到 11 年前
        1
  •  23
  •   Abe Heidebrecht    15 年前

    如果使用绑定,则是可能的。看起来有点奇怪,但这确实有效:

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

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

        2
  •  4
  •   Thomas Levesque    15 年前

    安倍的回答在大多数情况下都应该有效。另一个选择是延长 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;
        }
    }