2013-02-01 52 views
0

我有一個兩個窗口基本系統不使用System.Windows.Forms但System.Windows.Controls,其中一個創建一個FontDialog,所以我不得不包含System.Windows.Forms,因爲否則我將無法使用字體對話框。在另一個窗口中,我有一個RichTextBox,它應該使用在另一個窗口的FontDialog中選擇的字體/大小/樣式。c#解析字體錯誤

這對於創建FontDialog類的窗口類:

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 =克;」:

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 
+0

除了你的Window1有點醜陋以外,還要拆分你的排隊並進行調試。你究竟在哪裏得到這個異常:它在'cvt.ConvertFromString()','FontFamily ='中,在...?另外,是字體大小的逗號扔你嗎? –

+0

@lc。它在this.textBox2.FontFamily = g崩潰;如果我評論它然後它不會崩潰 –

+0

好吧,那麼你從'cvt.ConvertFromString(s)'中得到什麼?注意你使用'as' *而不檢查你是否得到一個空結果......不知道你爲什麼不投。 –

回答

0

解決:

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; 

兩個輸出相等。