wpf Application.LoadComponent 找不到资源
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15336917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Application.LoadComponent cannot find resource
提问by thecoop
I have a xaml file in my project at Ns1\Ns2\myfile.xaml. It's build action is set to Page, with a custom tool of MSBuild:Compile. I'm trying to load this file in a static constructor:
我的项目中有一个 xaml 文件,位于Ns1\Ns2\myfile.xaml. 它的构建操作设置为 Page,使用自定义工具 MSBuild:Compile。我正在尝试在静态构造函数中加载此文件:
namespace Ns1.Ns2 {
internal class MyClass {
static() {
var obj = Application.LoadComponent(new Uri("/myfile.xaml", UriKind.Relative));
}
}
}
However, when I try to run this code, it fails with an exception cannot locate resource 'myfile.xaml'. If I change the URI to an absolute URI:
但是,当我尝试运行此代码时,它失败并出现异常cannot locate resource 'myfile.xaml'。如果我将 URI 更改为绝对 URI:
var obj = Application.LoadComponent(new Uri("pack://application:,,,/ns1/ns2/myfile.xaml", UriKind.Absolute));
it fails with Cannot use absolute URI. I get the same errors if I change the type of myfile.xaml to Resource.
它失败了Cannot use absolute URI。如果将 myfile.xaml 的类型更改为 Resource,我会收到相同的错误。
How can I compile and reference myfile.xaml from code?
如何从代码编译和引用 myfile.xaml?
回答by Eli Arbel
You should specify the assembly name:
您应该指定程序集名称:
Application.LoadComponent(new Uri("/AssemblyName;component/myfile.xaml", UriKind.Relative))
Alternatively, if the file has a code-behind class, you can just 'new' it, and the generated code will load the associated XAML.
或者,如果文件具有代码隐藏类,您可以“新建”它,生成的代码将加载关联的 XAML。

