2009-04-10 65 views
1

是否可以從磁盤(即不是從應用程序資源)加載xaml文件並創建對象樹而不創建外部對象?換句話說,我想創建一個從Window派生的類並從磁盤加載一個xaml文件。看來我可以創建一個不從Window派生的類,並且可以從磁盤加載,或者我可以創建一個從Window派生的類,但是從應用程序資源加載xaml。如何在不創建外部對象的情況下加載xaml文件?

例如,我可以這樣做:

XmlTextReader xmlReader = new XmlTextReader("c:\\mywindow.xaml"); 
object obj = XamlReader.Load(xmlReader); 
Window win = obj as Window; 

但我真正想做的事情是這樣的:

class MyWindow : Window 
{ 
    public MyWindow() 
    { 
     System.Uri resourceLocater = new System.Uri("file://c:/mywindow.xaml", UriKind.Absolute); 
     System.Windows.Application.LoadComponent(this, resourceLocater); 
    } 
} 
... 
MyWindow w = new MyWindow(); 

目前的代碼的第二位給出了一個例外,說的URI不能是絕對的。

+0

真是個好主意,窗戶或只是在等待被使用的組件庫 - 輝煌。 – MrTelly 2009-04-10 05:11:03

回答

1

您可以將XAML文件的內容加載到一個字符串,然後解析內容,就像這樣:

 try 
     { 
      string strXaml = String.Empty; 
      using (var reader = new System.IO.StreamReader(filePath, true)) 
      { 
       strXaml = reader.ReadToEnd(); 
      } 

      object xamlContent = System.Windows.Markup.XamlReader.Parse(strXaml); 
     } 
     catch (System.Windows.Markup.XamlParseException ex) 
     { 
      // You can get specific error information like LineNumber from the exception 
     } 
     catch (Exception ex) 
     { 
      // Some other error 
     } 

那麼你應該能夠在xamlContent設置爲窗口的內容屬性。

Window w = new Window(); 
w.content = xamlContent; 
w.ShowDialog(); 
0

我不確定你可以使用絕對路徑加載程序集,指向文件系統上的某個文件。

我前幾天也有類似的問題,也許我的帖子能有所幫助(看我的答案編輯):

Load a ResourceDictionary from an assembly

編輯:我剛纔看到你想加載一個xaml,而不是一個程序集?然後檢查System.Windows.Markup.XamlReader,也許這是你正在尋找的。

相關問題