【问题标题】:Cannot compile project when declaring a XAML Resource Dictionary in code在代码中声明 XAML 资源字典时无法编译项目
【发布时间】:2016-11-10 13:05:22
【问题描述】:

我有一个名为 EditorResources.xaml 的 Resource Dictionary,它包含以下代码:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:editors="clr-namespace:MyCompany.Editors">

    <DataTemplate x:Key="PasswordEditorDataTemplate">
    </DataTemplate>
</ResourceDictionary>

但是当我在一个类中包含这行代码时:

private EditorResources res = new EditorResources();

它不会编译我的项目。我没有在.NET IDE 中显示任何Errors List 视图,但是当我查看我的Output 视图时,它显示以下错误:

错误 CS0246:找不到类型或命名空间名称“EditorResources”(您是否缺少 using 指令或程序集引用?)

但是,我不认为缺少引用,因为资源字典和类都在同一个项目(同一级别)中,我可以清楚地看到 EditorResources 类型突出显示为 TypeIntelliSense 踢当我点击我的“。”时,正如预期的那样。键并显示与Resource Dictionary 相关的属性,即.MergeDictionaries 等...

更新:

如果像我一样,您已将资源字典 (editorresources.xaml) 存储在子文件夹 (Editors) 中,并且您的程序集称为“MyCompany.Activity.Shared”,例如,不要忘记包含组件部分中的子文件夹,以便在调用@DrewNoakes 提供的代码时,可以毫无问题地调用以下内容:

var res = new ResourceDictionary
{
   Source = new Uri("/MyCompany.Activity.Shared;component/editors/editorresources.xaml",
   UriKind.RelativeOrAbsolute)
};

一旦你有了你的对象,你就可以通过代码访问你的 DataTemplates 或其他。

【问题讨论】:

  • 您是否尝试清理项目并重新构建它或重新启动VS?
  • 拥有EditorResources.xaml 文件并不意味着您可以实例化一个 EditorResources。你知道如何在代码中使用资源字典吗? (不知道为什么你会需要这个......)

标签: c# .net wpf winforms xaml


【解决方案1】:

您似乎有一个EditorResources.xaml 文件,但没有相应的EditorResources.xaml.cs 文件。

在这种情况下,您的 XAML 文件定义的类型是 ResourceDictionary。如果您希望拥有它的子类,则需要定义部分支持类并在 XAML 中添加相关属性以将它们链接在一起。

如果您不需要任何幕后的 C# 代码,只需直接加载 ResourceDictionary

这样的一些代码可能会有所帮助:

var dict = new ResourceDictionary
{
    Source = new Uri("/YourAssemblyName;component/EditorResources.xaml",
                     UriKind.RelativeOrAbsolute)
}

【讨论】:

  • 我已经尝试了你的建议,但我得到了An exception of type 'System.IO.IOException' occurred in PresentationFramework.dll but was not handled in user code - Additional information: Cannot locate resource 'editorresources.xaml'. 我已经设置了我的程序集有和没有“.dll”但无济于事。我是否必须将 EditorResources.xaml 设置为另一种类型,即 Embedded?
  • 是的,您需要对文件类型进行试验。可能是contentembedded resource,我不记得了。
  • 还是不行!我在 stackoverlow 上找到了其他链接,说明与您的解决方案相同,并且我尝试了各种建议,但仍然没有运气!痛,但我会继续寻找。谢谢。
  • 也许尝试更改Uri 中使用的路径以及UriKind。如果它在同一个程序集中,可能使用"EditorResources.xaml", UriKind.Relative
  • 破解它(侥幸!)。我正要放弃并决定使用 Partial 类选项,但它不喜欢部分类构造函数中的InitializeComponent,但是当我按 F12 查看我的 InitializeComponent 是否真的存在于基类中时,它把我带到了EditorResources.g.i.cs,其中包含完整的Uri。我的字典和班级试图在名为 Editors 的子文件夹中访问它,因此完整路径必须是 Source = new Uri("/MyCompany.Activity.Shared;component/editors/editorresources.xaml",UriKind.RelativeOrAbsolute)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-09
  • 2011-04-01
相关资源
最近更新 更多