user9107638
user9107638

Reputation:

Change FontSize in App resource from code behind

For a WPF TextBox control, I set the FontSize using a XAML style in my app.xaml like this:

<System:Double x:Key="FontSizeVal">12</System:Double>

<Style TargetType="{x:Type TextBlock}">
    <Setter Property="FontSize" Value="{DynamicResource FontSizeVal}"/>
</Style>

I want change FontSizeVal from Code Behind instead. I tried to use the below code, but it did not work (System.InvalidCastException: 'Specified cast is not valid.'):

App.Current.Resources["FontSizeVal"] = 10;

How can I set the FontSizeVal in code instead of in the XAML?

UPDATE:
my problem fixed, i changed : 10 to 10.0 tnx to @ash

Upvotes: 1

Views: 2484

Answers (1)

ASh
ASh

Reputation: 35693

summary

10 literal is interpreted as int here. use 10.0 which is double


here is some invetigation details

Q: what does App.Current.Resources["FontSizeVal"] = 10; do?

A: it replaces double resource with int resource. it is safe operation on its own

Q: why InvalidCastException?

A: due to DynamicResource behavior, TextBlock tries to apply int value resource to FontSize, but! FontSize expects double

if you try to set int value to FontSize via DP property

myTextBlock.SetValue(TextElement.FontSizeProperty, 10);

it throws "ArgumentException": 10 is not valid value for "FontSize" property.

setting double works!

myTextBlock.SetValue(TextElement.FontSizeProperty, 10.0);

and finally setting int via property wrapper:

myTextBlock.FontSize = 10;

it works because there is implicit cast from int to double.

Upvotes: 3

Related Questions