在WPF的XAML里一句代码就可以实现FontFamily的列表:
<ComboBox ItemsSource="{x:Static Fonts.SystemFontFamilies}">
如果需要显示的内容以相应的字体呈现,那么改成:
<ComboBox ItemsSource="{x:Static Fonts.SystemFontFamilies}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" FontFamily="{Binding}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
这时你会发现鼠标点击ComboBox时,字体加载速度很慢。因为WPF中,只有ComboBox控件没有使用VirtualizingStackPanel。
在Windows资源添加如下代码:
<Window.Resources>
<ItemsPanelTemplate x:Key="VSP">
<VirtualizingStackPanel/>
</ItemsPanelTemplate>
</Window.Resources>
然后,ComboBox改成:<ComboBox ItemsSource="{x:Static Fonts.SystemFontFamilies}" ItemsPanel="{StaticResource VSP}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" FontFamily="{Binding}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
就可以了,加载速度就非常快了。
以上显示都是英文的字体,如果需要显示中文字体。需要显示中文字体方法如下:
XAML:
<Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525" Loaded="win_LoadedEvent"> <Grid> <ComboBox x:Name="cbo_Demo" Margin="0,0,291,287"></ComboBox> </Grid> </Window>
Code:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Markup; namespace WpfApplication1 { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } public void win_LoadedEvent(object sender, RoutedEventArgs e) { foreach (FontFamily _f in Fonts.SystemFontFamilies) { LanguageSpecificStringDictionary _fontDic = _f.FamilyNames; if (_fontDic.ContainsKey(XmlLanguage.GetLanguage("zh-cn"))) { string _fontName = null; if (_fontDic.TryGetValue(XmlLanguage.GetLanguage("zh-cn"), out _fontName)) { cbo_Demo.Items.Add(_fontName); } } } } } }