【问题标题】:How do I load a xaml file without creating the outer object?如何在不创建外部对象的情况下加载 xaml 文件?
【发布时间】:2012-05-09 21:55:54
【问题描述】:

是否可以从磁盘(即不是从应用程序资源)加载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 不能是绝对的。

【问题讨论】:

  • 真是个好主意,窗口库或组件库正在等待使用 - 太棒了。

标签: c# wpf


【解决方案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 的 Content 属性。

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

【讨论】:

    【解决方案2】:

    我不确定您是否可以加载带有绝对路径的程序集,指向文件系统上某处的文件。

    几天前我遇到了类似的问题,也许我的帖子可以有所帮助(查看我的答案的编辑):

    Load a ResourceDictionary from an assembly

    编辑:我刚刚看到您要加载 xaml,而不是程序集?然后检查 System.Windows.Markup.XamlReader,也许这就是你要找的。​​p>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-14
      • 2015-11-14
      • 2015-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多