Wednesday, April 20, 2011

How do I load a xaml file without creating the outer object?

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.

From stackoverflow
  • 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):

    http://stackoverflow.com/questions/709087/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.

0 comments:

Post a Comment