1

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?

Shahryar
  • 39
  • 1
  • 3
  • 10
  • 1
    For this you will need a `DynamicResource` Refer to this question for more details: http://stackoverflow.com/questions/200839/whats-the-difference-between-staticresource-and-dynamicresource-in-wpf – vesan Oct 05 '15 at 22:37
  • 3
    using `DynamicResource` is not enough, the way you update the font is wrong, `font` is a variable and you simply set a new font to it, nothing will change if doing like that. You need to do something like this `Resources["FontFamilyName"] = new FontFamily("./Fonts/#Tahoma");` (the code is placed in the context of the current Window class). – Hopeless Oct 06 '15 at 06:33

1 Answers1

1

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.

WPF guy
  • 167
  • 10
AnjumSKhan
  • 9,647
  • 1
  • 26
  • 38