List The Fonts And Dynamically Change The Font Family In Windows 10 Universal App

Sometimes we need to give options to users to select a font family to use  with their own methods for implementation.

Let’s see the steps.

Create a new Windows 10 universal application and go to your MainPage.xaml.

Now add one listview control to list the font family and also add one control inside the ListView, for font name like the following xaml code. Add one textblock control to see the changes.

  1. <TextBlock x:Name="sampleTextBloxk" Text="Suresh M C# Corner MVP">  
  2. </TextBlock>  
  3. <ListView x:Name="FontListBox" SelectionChanged="FontListBox_SelectionChanged">  
  4.     <ListView.ItemTemplate>  
  5.         <DataTemplate>  
  6.             <TextBlock Text="{Binding fName}"></TextBlock>  
  7.         </DataTemplate>  
  8.     </ListView.ItemTemplate>  
  9. </ListView>  
Next go to code behind page and write the following code to get the list of fonts available in the system and assign it to the list. Before that we need to add the NuGet package “Win2D.uwp” like the following image.

  1. public void getFontList()  
  2. {  
  3.     List < fonts > fList = newList < fonts > ();  
  4.     string[] fontList = Microsoft.Graphics.Canvas.Text.CanvasTextFormat.GetSystemFontFamilies();  
  5.     foreach(var font in fontList)  
  6.     {  
  7.         fList.Add(newfonts()  
  8.         {  
  9.             fName = string.Format("Font: {0}", font)  
  10.         });  
  11.     }  
  12.     FontListBox.ItemsSource = fList;  
  13. }  
Next get the selected font name from user and assign to textblock control using the following code.
  1. private void FontListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)  
  2. {  
  3.    var selectedFont= e.AddedItems[0].ToString();  
  4.    sampleTextBloxk.FontFamily = newFontFamily(selectedFont);  
  5. }  
When user selects a Font it will change the font and it will be lost when the user exits the  app. Suppose you want to save the font family, an easy way is to store it using ApplicationDataContatineer.
  1. Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;  
  2. localSettings.Values["Myfonts"] = selectedFont;  
You can retrieve the values from anywhere in the application by using the following code.
  1. object value = localSettings.Values["Myfonts"];  
Run the application and see the expected output like the following image.


For more information on Windows 10 UWP, refer to my e-book:

Up Next
    Ebook Download
    View all
    View all