简体   繁体   中英

How does use XamlReader to load from a Xaml file from within the assembly?

I've found several posts across stackoverflow and the rest of the internet regarding how to load Xaml from a static file: they recommend creating a XmlReader or StreamReader pointing to a file found on the file system, but the .xaml document I would like to read from is going to be compiled with the rest of the assembly, so it won't have a meaningful file Uri. I do not want to copy this document around wherever the assembly goes. Is there a way to read from a .xaml document that has been compiled into the assembly?

I also know that I can simply read from a very long string literal inside the code itself, but I'd rather not do that - the UIElement produced from the Xaml should be easily edited, and I gain this by editing it in a Xaml file.

To illustrate what I'm hoping for, here's an example:

private void LoadUIElementFromCompiledXaml()
{
    XmlReader xmlReader = new XmlReader("*Uri for .xaml document within my assembly*");
    UIElement elementLoaded = (UIElement)XamlReader.Load(xmlReader);
}

I apologize in advance if the answer is blatantly obvious.

Before you can load Xaml from an assembly as an embedded resource, there is a bit of setup you must do. I'll walk you through an example, then from there you can customize it to suite your needs.

  1. Create folder in your project. Name it XAML.
  2. Add a XAML file to the XAML folder. Lets call it Sample.xaml.
  3. Right-click on Sample.Xaml and choose properties. Set the value for Build Action to "Embedded Resource".
  4. Right-click on the project and choose properties. Take note of the Default namespace value. We will use this as part of the path. For this example lets assume it is "MyNamespace.

Your code to load the Xaml resource would look something like this:

string defaultNamespace = "MyNamespace";
string folderName = "XAML";
string fileName = "Sample.xaml";

string path = String.Format("{0}.{1}.{2}", defaultNamespace, folderName, fileName);

using (Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(path))        
{
    object root = XamlReader.Load(stream);
}

As you can see the path to the resource is made up of the default namespace of the project, the folder path to the file, and the file name. If the folder path has multiple levels use dots as folder separator in place of back slashes. For example Xaml\\Subfolder would be Xaml.Subfolder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM