1
更新靜態資源價值我有類似下面的代碼:WPF - 在運行時
<Application
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Software_Suite_Maker"
xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" x:Class="WpfApplication1.App"
StartupUri="MainWindow.xaml">
<Application.Resources>
<FontFamily x:Key="FontFamilyName">./Fonts/#Segoe UI</FontFamily>
</Application.Resources>
和窗口XAML代碼是:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox FontFamily="{StaticResource FontFamilyName}" Margin="135,122,187,180" Text="test"/>
<Button FontFamily="{StaticResource FontFamilyName}" Margin="135,144,329,154" Content="test"/>
</Grid>
現在我想要從後面的代碼中更改FontFamilyName的值。我寫了這樣的代碼:
var font = TryFindResource("FontFamilyName") as FontFamily;
font = new FontFamily("./Fonts/#Tahoma");
但是什麼都沒有發生,也沒有改變。 我的問題是:如何從後面的代碼更改FontFamilyName值,還會對對象進行更改?
爲此,您需要一個'DynamicResource'參考這個問題的更多細節:http://stackoverflow.com/questions/200839/whats-the-difference-between-staticresource-in-wpf – vesan
使用DynamicResource是不夠的,你更新字體的方式是錯誤的,font是一個變量,你只需要設置一個新的字體爲如果這樣做,沒有什麼會改變。你需要做這樣的事情'''[FontFamilyName「] = new FontFamily(」./ Fonts /#Tahoma「);(代碼放置在當前Window類的上下文中)。 – Hopeless