Search code examples
c#xamlfontsfont-family

Fonts names in the Combobox List XAML c#


I'm designing a list of Fonts, where I refer to Fonts.SystemFontFamilies, but also I want to include 3 custom fonts that exist in my MyDllProject project. First I add the SystemFontFamilies, and works good, then I add my custom fonts (Roboto, Abstractus and OpenSans) and these add them well to the list, but it gives me the prefix ./#. So, I would like to find a way to show the names of the font just like Abstractus, Roboto and Open Sans without nothing else.

The code of the comboBox is

if( _cmbFontFamilies != null )
      {
            _cmbFontFamilies.ItemsSource = FontUtilities.Families.OrderBy( fontFamily => fontFamily.Source );

      }

and the code for FontUtilities is

  internal class FontUtilities
  {
    internal static IEnumerable<FontFamily> Families
    {
      get
      {
      foreach ( FontFamily font in Fonts.SystemFontFamilies)
      {
          yield return font;
      } 
      foreach (FontFamily fontFamily in Fonts.GetFontFamilies(new 
          Uri("pack://application:,,,/MyDllProject ;Component/Resources/")))
       {
          yield return fontFamily;
       }   
      }
    }    
  }

The result that I have. enter image description here


Solution

  • Each resulting FontFamily object returned by Fonts.GetFontFamilies has a friendly name of the form "./#Family Name". This friendly name sets a Source property of FontFamily and the value of Source property is returned by FontFamily.ToString() method.

    I would create a custom class FontName

    public class FontName
    {
        public string Name { get; set; }
    
        public string Source { get; set; }
    }
    

    and return a collection of FontName by FontUtilities.Families. When loading custom fonts remove prefix "./#"

    internal class FontUtilities
    {
        internal static IEnumerable<FontName> Families
        {
            get
            {
                foreach ( FontFamily font in Fonts.SystemFontFamilies)
                {
                    yield return new FontName { Name = font.Source, Source = font.Source };
                } 
                foreach (FontFamily fontFamily in Fonts.GetFontFamilies(new 
              Uri("pack://application:,,,/MyDllProject ;Component/Resources/")))
                {
                  yield return new FontName { Name = fontFamily.Source.Replace("./#", string.Empty), Source = fontFamily.Source };
                }   
            }
        }    
    }
    
    
    if( _cmbFontFamilies != null )
    {
        _cmbFontFamilies.SelectedValuePath = "Source";
        _cmbFontFamilies.DisplayValuePath = "Name";
        _cmbFontFamilies.ItemsSource = FontUtilities.Families.OrderBy( fontFamily => fontFamily.Source );
    
    }