![](/img/trans.png)
[英]How to change the fontsize of Data Grid Header from code behind wpf
[英]Change FontSize in App resource from code behind
对于 WPF TextBox 控件,我在 app.xaml 中使用 XAML 样式设置 FontSize,如下所示:
<System:Double x:Key="FontSizeVal">12</System:Double>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="FontSize" Value="{DynamicResource FontSizeVal}"/>
</Style>
我想从代码FontSizeVal
更改FontSizeVal
。 我尝试使用下面的代码,但它不起作用(System.InvalidCastException: 'Specified cast is not valid.'):
App.Current.Resources["FontSizeVal"] = 10;
如何在代码中而不是在 XAML 中设置FontSizeVal
?
更新:
我的问题解决了,我改了:10 到 10.0 tnx 到 @ash
概括
10
文字在这里被解释为int
。 使用double
10.0
这是一些调查细节
问:什么App.Current.Resources["FontSizeVal"] = 10;
做?
A:它用int资源替换了double资源。 它本身是安全的操作
问:为什么是InvalidCastException
?
A:由于 DynamicResource 行为,TextBlock 尝试将int
值资源应用于 FontSize,但是! FontSize 期望double
如果您尝试通过 DP 属性将int
值设置为 FontSize
myTextBlock.SetValue(TextElement.FontSizeProperty, 10);
它抛出“ArgumentException”:10 不是“FontSize”属性的有效值。
设置双重作品!
myTextBlock.SetValue(TextElement.FontSizeProperty, 10.0);
最后通过属性包装器设置int
:
myTextBlock.FontSize = 10;
它起作用是因为有从int
到double
隐式转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.