2

Is it possible to load a xaml file from disk (ie not from an application resource) and create the object tree without creating the outer object? In other words, I want to create a class that derives from Window and loads a xaml file from disk. It seems I can either create a class that does not derive from Window and can load from disk, or I can create a class that derives from Window but loads the xaml from an application resource.

For example, I can do this:

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

but what I really want to do is this:

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();

Currently the second bit of code gives an exception saying that the uri cannot be absolute.

dan gibson
  • 3,605
  • 3
  • 39
  • 57

2 Answers2

1

You can load the content of a XAML file into a string and then parse the content, like this:

        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
        }

Then you should be able to set the xamlContent to the Content property of the Window.

Window w = new Window();
w.content = xamlContent;
w.ShowDialog();
TGasdf
  • 1,220
  • 12
  • 14
0

I'm not sure you can load an assembly with an absolute path, pointing to a file somewhere on the file system.

I had a similar problem a few days ago, maybe my post can be of help (look at the edit of my answer):

Load a ResourceDictionary from an assembly

edit: I just saw you want to load a xaml, not an assembly? Then check up on System.Windows.Markup.XamlReader, maybe this is what you are looking for.

Community
  • 1
  • 1
Christian Hubmann
  • 1,502
  • 3
  • 17
  • 21