【问题标题】:Change FontSize in App resource from code behind从后面的代码更改 App 资源中的 FontSize
【发布时间】:2017-12-16 17:00:07
【问题描述】:

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

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

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

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

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

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

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

【问题讨论】:

  • “不工作”没有解释程序中的发生了什么。它会抛出运行时异常吗?或者 UI 中有一个 TextBlock 并且它仍然具有相同的 12 字体大小?还是别的什么?请澄清
  • System.InvalidCastException: '指定的演员表无效。'
  • 10 文字在这里被解释为int。试试10.0
  • tnx 这对我有用。

标签: c# wpf resourcedictionary wpf-style


【解决方案1】:

总结

10 文字在这里被解释为int。使用10.0,即double


这里有一些调查细节

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;

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

【讨论】:

    猜你喜欢
    • 2016-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-16
    相关资源
    最近更新 更多