Change FontSize in App resource from code behind

☆樱花仙子☆ 提交于 2021-02-05 08:12:09

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/47848017/change-fontsize-in-app-resource-from-code-behind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!