2015-10-05 79 views
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值,还会对对象进行更改?

+1

为此,您需要一个'DynamicResource'参考这个问题的更多细节:http://stackoverflow.com/questions/200839/whats-the-difference-between-staticresource-in-wpf – vesan

+2

使用DynamicResource是不够的,你更新字体的方式是错误的,font是一个变量,你只需要设置一个新的字体为如果这样做,没有什么会改变。你需要做这样的事情'''[FontFamilyName“] = new FontFamily(”./ Fonts /#Tahoma“);(代码放置在当前Window类的上下文中)。 – Hopeless

回答

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