C# 分析字体错误

本文关键字:错误 字体 | 更新日期: 2023-09-27 17:56:51

我有两个窗口基本系统,不使用System.Windows.Forms,而是使用System.Windows.Controls,其中一个创建一个FontDialog,所以我必须包含System.Windows.Forms,否则我将无法拥有字体对话框。在另一个窗口中,我有一个富文本框,它应该使用在另一个窗口的字体对话框中选择的字体/大小/样式。

这是创建字体对话框的窗口的类:

public partial class Window1 : Window
{
    public FontDialog font;
    public Window1(String name)
    {
        InitializeComponent();
        this.textBox1.Text = name;
    }
    private void button2_Click(object sender, RoutedEventArgs e)
    {
        font = new FontDialog();
        font.ShowDialog();
    }
}

在这里,我调用 Window1 并尝试使用其字体。

private void button2_Click(object sender, RoutedEventArgs e)
{
    Window1 a = new Window1(this.name);
    a.ShowDialog();
    var cvt = new FontConverter();
    string s = cvt.ConvertToString(a.font.Font);
    Console.Out.WriteLine("Value is: " + s);
    System.Windows.Media.FontFamily g = (System.Windows.Media.FontFamily) cvt.ConvertFromString(s);
    if (g != null)
    {
         this.textBox2.FontFamily = g;
    }
}

它准确地输出在 FontDialog 中选择的内容,但随后在"this.textBox2.FontFamily = g;"行处崩溃:

Value is: Microsoft Sans Serif; 8,25pt
'_.NetworkingGT_Incrementer.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:'Windows'Microsoft.Net'assembly'GAC_MSIL'WindowsBase.resources'v4.0_4.0.0.0_pt-BR_31bf3856ad364e35'WindowsBase.resources.dll'
A first chance exception of type 'System.ArgumentException' occurred in WindowsBase.dll
A first chance exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll
A first chance exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll
'_.NetworkingGT_Incrementer.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:'Windows'Microsoft.Net'assembly'GAC_MSIL'System.Xaml.resources'v4.0_4.0.0.0_pt-BR_b77a5c561934e089'System.Xaml.resources.dll'
A first chance exception of type 'System.Xaml.XamlObjectWriterException' occurred in System.Xaml.dll
A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll
An unhandled exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll

C# 分析字体错误

已解决:

var cvt = new FontConverter();
string s = cvt.ConvertToString(a.font.Font);
Console.Out.WriteLine("Value is: " + s);
System.Windows.Media.FontFamily g = new System.Windows.Media.FontFamily(s);
Console.Out.WriteLine("Value is: " + g.ToString());
this.textBox2.FontFamily = g;

两个输出相等。