![](/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.