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!
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With