Shahryar
Shahryar

Reputation: 49

WPF - Update static resource value at runtime

I have code similar to the following:

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

and the Window xaml code is:

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

Now I want to change the value of FontFamilyName from behind code. I wrote this code:

var font = TryFindResource("FontFamilyName") as FontFamily;
font = new FontFamily("./Fonts/#Tahoma");

But nothing happened and did not change. My question is: How can I change FontFamilyName value from behind code and changes will also be made on the objects?

Upvotes: 1

Views: 3674

Answers (1)

AnjumSKhan
AnjumSKhan

Reputation: 9827

You have to use a DynamicResource for that :

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

Provides a value for any XAML property attribute by deferring that value to be a reference to a defined resource. Lookup behavior for that resource is analogous to run-time lookup.

Upvotes: 1

Related Questions