Application.LoadComponent找不到资源(Application.LoadComponent cannot find resource)

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

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

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

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

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

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

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:

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:

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.

How can I compile and reference myfile.xaml from code?

最满意答案

您应该指定程序集名称:

Application.LoadComponent(new Uri("/AssemblyName;component/myfile.xaml", UriKind.Relative))

另外,如果文件有一个代码隐藏类,你可以'新建'它,生成的代码将加载关联的XAML。

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.

更多推荐