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

本文关键字:静态 资源 更新 运行时 WPF | 更新日期: 2023-09-27 18:16:20

我有类似于下面的代码:

<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>

和windows 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值从后面的代码和更改也将对对象进行?

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

你必须使用DynamicResource:

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

在MSDN上阅读关于DynamicResource:

通过将该值延迟为对已定义资源的引用,为任何XAML属性提供值。该资源的查找行为类似于运行时查找。