Application.LoadComponent无法找到资源

the*_*oop 8 .net wpf resources

我的项目中有一个xaml文件Ns1\Ns2\myfile.xaml.它的构建操作设置为Page,使用MSBuild的自定义工具:编译.我正在尝试在静态构造函数中加载此文件:

namespace Ns1.Ns2 {
    internal class MyClass {
        static() {
            var obj = Application.LoadComponent(new Uri("/myfile.xaml", UriKind.Relative));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试运行此代码时,它会失败并出现异常cannot locate resource 'myfile.xaml'.如果我将URI更改为绝对URI:

var obj = Application.LoadComponent(new Uri("pack://application:,,,/ns1/ns2/myfile.xaml", UriKind.Absolute));
Run Code Online (Sandbox Code Playgroud)

它失败了Cannot use absolute URI.如果我将myfile.xaml的类型更改为Resource,我会得到相同的错误.

如何从代码编译和引用myfile.xaml?

Eli*_*bel 13

您应该指定程序集名称:

Application.LoadComponent(new Uri("/AssemblyName;component/myfile.xaml", UriKind.Relative))
Run Code Online (Sandbox Code Playgroud)

或者,如果文件具有代码隐藏类,则可以"新"它,生成的代码将加载关联的XAML.

  • @EyalPerry它是一个相对URI,因为它没有指定方案.在这种情况下,绝对URI将是`pack:// application:,,,/AssemblyName; component/myfile.xaml`注意`LoadComponent`不接受绝对URI. (2认同)