WPF - 在运行时更新静态资源值

时间:2015-10-05 22:12:10

标签: c# 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>

和Window 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值,还会对对象进行更改?

1 个答案:

答案 0 :(得分:1)

你必须为DynamicResource:

<TextBox FontFamily="{DynamicResource FontFamilyName}" Margin="135,122,187,180" Text="test"/>
<Button FontFamily="{DynamicResource FontFamilyName}" Margin="135,144,329,154" Content="test"/>

Read on MSDN about DynamicResource