玩转字体





5.00/5 (5投票s)
在WPF中玩转字体
我一直在玩WPF的RichTextBox
,并决定添加字体选择功能会是个好主意。 显然,既然是WPF,我不想仅仅列出字体,而是想以它们实际显示的方式列出字体。 换句话说,我想使用字体本身来书写字体名称。 到现在,这不应该让你感到惊讶,因为在WPF中做到这一点非常容易。
首先,获取字体列表非常容易。.NET提供了一个方便的类,巧妙地命名为InstalledFontCollection
,所以我们将它包装成一个方便的列表,准备使用。
using System;
using System.Collections.Generic;
using System.Drawing.Text;
using System.Drawing;
namespace FontManager
{
public class InstalledFonts : List<FontFamily>
{
public InstalledFonts()
{
InstalledFontCollection fonts = new InstalledFontCollection();
this.AddRange(fonts.Families);
}
}
}
这个类只是将已安装的字体族包装成一个方便的数据提供格式。 这完全是为了方便与Blend的集成。
接下来,我们需要定义一个usercontrol
来显示字体。 需要注意的是,我们使用虚拟化堆叠面板来显示数据 - 如果不这样做,你可能需要等待很长时间才能首次显示字体。
<UserControl
x:Class="FontManager.InstalledFontDisplay"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:drawing="clr-namespace:System.Drawing;assembly=System.Drawing"
xmlns:m="clr-namespace:FontManager"
xmlns:sys="clr-namespace:System.Collections.Generic;assembly=mscorlib"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<UserControl.Resources>
<Style x:Key="FontStyle">
<Setter Property="Control.FontFamily" Value="{Binding Name}" />
<Setter Property="Control.FontSize" Value="16" />
</Style>
<DataTemplate x:Key="FontTemplate">
<StackPanel VirtualizingStackPanel.IsVirtualizing="True">
<TextBlock
Text="{Binding Name}"
ToolTip="{Binding Name}"
Style="{StaticResource FontStyle}" />
</StackPanel>
</DataTemplate>
<ObjectDataProvider x:Key="FontProvider" ObjectType="{x:Type m:InstalledFonts}"/>
</UserControl.Resources>
<ComboBox
VerticalAlignment="Top"
ItemsSource="{Binding Source={StaticResource FontProvider}}"
ItemTemplate="{StaticResource FontTemplate}" />
</UserControl>
就是这样 - 这就是以适当的字体显示字体名称的所有内容。 这非常简单,也是喜爱WPF的又一个原因。 继续吧 - 你知道你爱它。