从后面的代码更改应用程序资源中的字体大小 [英] Change FontSize in App resource from code behind

查看:46
本文介绍了从后面的代码更改应用程序资源中的字体大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于 WPF TextBox 控件,我在 app.xaml 中使用 XAML 样式设置 FontSize,如下所示:

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>

我想从代码隐藏中更改 FontSizeVal.我尝试使用下面的代码,但它不起作用(System.InvalidCastException: 'Specified cast is not valid.'):

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;

如何在代码中而不是在 XAML 中设置 FontSizeVal?

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

更新:
我的问题解决了,我改变了:10至10.0tnx 到@ash

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

推荐答案

总结

10 文字在这里被解释为 int.使用 10.0 这是 double

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

这里是一些调查细节

:App.Current.Resources["FontSizeVal"] = 10; 有什么作用?

A:它用 int 资源替换双资源.它本身是安全的操作

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

:为什么InvalidCastException?

A:由于 DynamicResource 行为,TextBlock 尝试将 int 值资源应用于 FontSize,但是!FontSize 需要 double

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

如果您尝试通过 DP 属性将 int 值设置为 FontSize

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

myTextBlock.SetValue(TextElement.FontSizeProperty, 10);

它抛出ArgumentException":10 不是FontSize"属性的有效值.

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

设置双重作品!

myTextBlock.SetValue(TextElement.FontSizeProperty, 10.0);

最后通过属性包装器设置int:

and finally setting int via property wrapper:

myTextBlock.FontSize = 10;

之所以有效,是因为从 intdouble 的隐式转换.

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

这篇关于从后面的代码更改应用程序资源中的字体大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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