绑定到组合框时出现SystemFontFamilies错误

sun*_*nny 5 wpf fonts

我列举了fontfamilies列表并绑定到combobox,问题是当系统中有一个字体被破坏时.整个应用程序将崩溃.任何方式我能够绑定到systemfontfamilies但能够跳过显示错误的字体?

如果itemtemplate中的fontfamily绑定被注释,则以下代码运行正常.

 <ComboBox x:Name="comboFonts"
                          Grid.IsSharedSizeScope="True"
                          Grid.Row="0" Grid.Column="1"
                          ItemsSource="{Binding Source={x:Static Member=Fonts.SystemFontFamilies}}"
                          SelectedItem="{Binding FontFamily, Mode=TwoWay}"
                          HorizontalAlignment="Stretch">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto" SharedSizeGroup="FontName"></ColumnDefinition>
                        <ColumnDefinition Width="*"></ColumnDefinition>
                    </Grid.ColumnDefinitions>
                    <TextBlock Text="{Binding Source}" HorizontalAlignment="Left"/>
                    <Label FontFamily="{Binding FallbackValue=Verdana}" HorizontalAlignment="Right">Sample</Label>
                </Grid>

            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>
Run Code Online (Sandbox Code Playgroud)

获得的错误消息如下

Message=Input file or data stream does not conform to the expected file format specification.
Source=PresentationCore
StackTrace:
   at MS.Internal.Text.TextInterface.Native.Util.ConvertHresultToException(Int32 hr)
   at MS.Internal.Text.TextInterface.Font.CreateFontFace()
   at MS.Internal.Text.TextInterface.Font.AddFontFaceToCache()
   at MS.Internal.Text.TextInterface.Font.GetFontFace()
Run Code Online (Sandbox Code Playgroud)

请帮忙.谢谢

Nat*_*net 5

我有同样的问题。在富文本框编辑器中,我用所有可用的字体系列填充功能区组合框,并将该字体附加到组合框中的特定项目,以便用户立即看到字体的外观。

当系统上存在 WPF 无法呈现的字体时,应用程序将崩溃。

查看事件查看器中的堆栈跟踪,我注意到 WPF 尝试实例化 System.Windows.Media.GlyphTypeface 类型的对象。我发现,当我尝试在代码中自己实例化该对象(通过 System.Windows.Media.Typeface 类型)并且 TryGetGlyphTypeface() 函数将为我的特定字体设置返回 false 时,该字体在 WPF 中不可用。

为我解决问题的代码:

    foreach (FontFamily aFontFamily in Fonts.SystemFontFamilies)
    {
        // Instantiate a TypeFace object with the font settings you want to use
        Typeface ltypFace = new Typeface(aFontFamily, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
        // Try to create a GlyphTypeface object from the TypeFace object
        GlyphTypeface lglyphTypeFace;
        if (ltypFace.TryGetGlyphTypeface(out lglyphTypeFace))
        {
            // Creation of the GlyphTypeface worked. You can use the font
            RibbonGalleryItem lribItem = new RibbonGalleryItem();
            lribItem.Content = aFontFamily.Source;
            lribItem.FontFamily = aFontFamily;
            lribGalCatFont.Items.Add(lribItem);
        }
    }
Run Code Online (Sandbox Code Playgroud)

为防止每次加载组合框时都必须执行此代码(因为它在用户控件中,所以执行次数非常多),我在应用程序启动时执行此操作,并将可用字体数组保存在全局变量中。