[英]How do I load a xaml file without creating the outer object?
是否可以從磁盤 (而不是從應用程序資源)加載xaml文件並創建對象樹而不創建外部對象? 換句話說,我想創建一個從Window派生並從磁盤加載xaml文件的類。 看來我可以創建一個不從Window派生並可以從磁盤加載的類,或者我可以創建一個從Window派生但從應用程序資源加載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不能是絕對的。
您可以將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的Content屬性。
Window w = new Window();
w.content = xamlContent;
w.ShowDialog();
我不確定您是否可以使用絕對路徑加載程序集,使其指向文件系統上某處的文件。
幾天前我遇到了類似的問題,也許我的帖子可能會對您有所幫助(請看我答案的編輯內容):
從程序集中加載ResourceDictionary
編輯 :我剛剛看到您要加載一個XAML,而不是程序集? 然后在System.Windows.Markup.XamlReader上進行檢查,也許這就是您想要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.