是否可以在WPF中为静态资源提供类型转换器? [英] Is it possible to supply a type converter for a static resource in WPF?

查看:251
本文介绍了是否可以在WPF中为静态资源提供类型转换器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个新手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}"/>

这将导致错误,因为Today被定义为整数资源,但是Text属性需要一个字符串.这个例子是人为设计的,但希望能说明这个问题.

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 hopefully illustrates the question.

问题是,除了使我的资源类型与属性类型完全匹配之外,我是否有办法为我的资源提供转换器?类似IValueConverter的绑定或类型转换器.

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.

谢谢!

推荐答案

使用绑定是可能的.似乎有点奇怪,但这实际上可以工作:

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

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

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

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.

这篇关于是否可以在WPF中为静态资源提供类型转换器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆