简体   繁体   中英

XML file accessible from XAML and code behind

Is it possible to have an XML file embedded in the project that can be accessed from code behind and directly from XAML using XMLDataProvider?

When I set the XML file as "Embedded Resource", I can access it from code, but not from XAML. When I set the XML file as "Resource", I can access it from XAML, but not from code.

Now it is possible to load a Resource from using a Pack Uri from code, however the xml file is in a 'service' library and I don't feel like referencing PresentationFramework, WindowBase, etc. to make this work.

External XML file is also not an option since a lot of unit tests will break. The solution would be to add an attribute to those tests, only there are A LOT.

Any suggestions?

You can easily set xml files are Resource and then read them in code as follows

        Uri uri = new Uri("/file.xml", UriKind.Relative);
        StreamResourceInfo info = Application.GetResourceStream(uri);
        if (info != null)
        {
            using (StreamReader reader = new StreamReader(info.Stream))
            {
                string xml = reader.ReadToEnd();
            }
        }

Here file.xml is Resource so replace to whatever name you have

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