Store and Read FontSize from Preferences

Jassim Al Rahma 1,516 Reputation points
2023-01-08T22:13:01.25+00:00

Hi,

In my app I am allowing the user to set the FontSize of the control using Settings page and I am setting the FontSize this way:

Preferences.Set("FontSize", SliderFontSize.Value.ToString());  

But then in my Styles file, How can I get that value to be set for the Label FontSize below?

<Style TargetType="Label">  
    <Setter Property="BackgroundColor" Value="Transparent" />  
    <Setter Property="FontFamily" Value="OpenSansRegular" />  
    <Setter Property="FontSize" Value="[READ THE VALUE FROM PREFERENCES" />  
</Style>  

Thanks,
Jassim

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
2,746 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 33,381 Reputation points Microsoft Vendor
    2023-01-09T03:08:01.37+00:00

    Hello,

    You could not invoke the c# method in XAML, except Value Convert.

    This is a preference that does not have an XAMl definition, so it cannot be referenced by XAML.

    Please refer to the following documentations about the best practices about theming an app on MAUI:

    Update:

    You could refer to Dynamic styles to get more details about how to set dynamic styles.

    For instance, you could follow the following steps to make your FontSize could be changed dynamically.

    Step 1: Add some size in your ResourceDictionary of App.xaml.

       <x:Int32 x:Key="smallSize">14</x:Int32> // the value must be int for fontsize.  
       <x:Int32 x:Key="normalSize">28</x:Int32>  
       <x:Int32 x:Key="largeSize">44</x:Int32>  
    

    Step 2: Add DynamicResource into your Label:

       <Label  
             Text="Hello, World!"  
             FontSize="{DynamicResource LabelFontSize}"  
             HorizontalOptions="Center" />  
    

    Step 3: Change the fontsize:

       Resources["LabelFontSize"] = App.Current.Resources["largeSize"];  
    

    Best Regards,

    Alec Liu.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.