Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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!

like image 675
Notre Avatar asked Mar 04 '10 19:03

Notre


People also ask

What is static resource in WPF?

Static Resource - Static resources are the resources which you cannot manipulate at runtime. The static resources are evaluated only once by the element which refers them during the loading of XAML.

What are converters in WPF?

The WPF converters acts as a bridge between the source and the target if the source and target have different data formats or need some conversion. For example, sometimes we need to convert data from one format to another format, when it flows from the source to the target or vice-versa the conversion is required.

How to add converter in ResourceDictionary?

To implement an IValueConverter one must create a class and then put the instance of that class in a ResourceDictionary within your UI. Once your class is part of a ResourceDictionary, you can point to the instance of the converter using the Converter property of Binding, along with a StaticResource markup extension.


1 Answers

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.

like image 110
Abe Heidebrecht Avatar answered Sep 28 '22 04:09

Abe Heidebrecht