diff --git a/ColorTextBlock.Avalonia/CCode.cs b/ColorTextBlock.Avalonia/CCode.cs index 265486f..2dfc228 100644 --- a/ColorTextBlock.Avalonia/CCode.cs +++ b/ColorTextBlock.Avalonia/CCode.cs @@ -2,47 +2,29 @@ using System.Collections.Generic; using System.Linq; using Avalonia.Media; +using Avalonia; +using ColorTextBlock.Avalonia.Fonts; namespace ColorTextBlock.Avalonia { public class CCode : CSpan { - private readonly static FontFamily Monospace; + public static readonly StyledProperty MonospaceFontFamilyProperty = + AvaloniaProperty.Register( + nameof(MonospaceFontFamily), + defaultValue: FontFamilyCollecter.TryGetMonospace() ?? FontFamily.Default, + inherits: true); - static CCode() + public CCode(IEnumerable inlines) : base(inlines) { - string[] RequestFamilies = { - "menlo", - "monaco", - "consolas", - "droid sans mono", - "inconsolata", - "courier new", - "monospace", - "droid sans fallback" - }; - - var monospaceName = FontManager.Current.GetInstalledFontFamilyNames() - .Where(name => RequestFamilies.Any(reqNm => name.ToLower().Contains(reqNm))) - .FirstOrDefault(); - - if (String.IsNullOrEmpty(monospaceName)) - { - // giveup - Monospace = null; - } - else - { - Monospace = new FontFamily(monospaceName); - } + var obsvr = this.GetBindingObservable(MonospaceFontFamilyProperty); + Bind(FontFamilyProperty, obsvr); } - public CCode(IEnumerable inlines) : base(inlines) + public FontFamily MonospaceFontFamily { - if (Monospace != null) - { - FontFamily = Monospace; - } + get { return GetValue(MonospaceFontFamilyProperty); } + set { SetValue(MonospaceFontFamilyProperty, value); } } } } diff --git a/ColorTextBlock.Avalonia/Fonts/FontFamilyCollecter.cs b/ColorTextBlock.Avalonia/Fonts/FontFamilyCollecter.cs new file mode 100644 index 0000000..9888a73 --- /dev/null +++ b/ColorTextBlock.Avalonia/Fonts/FontFamilyCollecter.cs @@ -0,0 +1,33 @@ +using Avalonia.Media; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace ColorTextBlock.Avalonia.Fonts +{ + internal class FontFamilyCollecter + { + public static FontFamily TryGetMonospace() + { + string[] RequestFamilies = { + "menlo", + "monaco", + "consolas", + "droid sans mono", + "inconsolata", + "courier new", + "monospace", + "droid sans fallback" + }; + + var monospaceName = FontManager.Current.GetInstalledFontFamilyNames() + .Where(name => RequestFamilies.Any(reqNm => name.ToLower().Contains(reqNm))) + .FirstOrDefault(); + + return String.IsNullOrEmpty(monospaceName) ? + null : + new FontFamily(monospaceName); + } + } +}