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.
- <TextBlock x:Name="sampleTextBloxk" Text="Suresh M C# Corner MVP">
- </TextBlock>
- <ListView x:Name="FontListBox" SelectionChanged="FontListBox_SelectionChanged">
- <ListView.ItemTemplate>
- <DataTemplate>
- <TextBlock Text="{Binding fName}"></TextBlock>
- </DataTemplate>
- </ListView.ItemTemplate>
- </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.
- public void getFontList()
- {
- List < fonts > fList = newList < fonts > ();
- string[] fontList = Microsoft.Graphics.Canvas.Text.CanvasTextFormat.GetSystemFontFamilies();
- foreach(var font in fontList)
- {
- fList.Add(newfonts()
- {
- fName = string.Format("Font: {0}", font)
- });
- }
- FontListBox.ItemsSource = fList;
- }
Next get the selected font name from user and assign to textblock control using the following code.
- private void FontListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- var selectedFont= e.AddedItems[0].ToString();
- sampleTextBloxk.FontFamily = newFontFamily(selectedFont);
- }
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.
- Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
- localSettings.Values["Myfonts"] = selectedFont;
You can retrieve the values from anywhere in the application by using the following code.
- 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: