Произошла ошибка при поиске словаря ресурсов wpf

I’m in the process of building a WPF application and ran into an error when trying to reference a resource dictionary. Inside my WPF application project I have a folder called «Styles» to contain all the xaml style templates for my app:

VS2010 Solution Explorer

In my app.xaml file I have this:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Styles/MetroTheme.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

However, when I hover over the source property I get an error saying «An error occurred while finding the resource dictionary «Styles/MetroTheme.xaml». I can see the xaml file inside the folder both in Visual Studio and in the file system.

I have also tried «/Styles/MetroTheme.xaml» and a pack uri for the source property, both with no success. Any idea why I’m getting this file not found error?

asked Jun 15, 2012 at 15:09

Steven Ball's user avatar

1

I had the same issue, but setting Build Action = Page did not solve for me. Turned out I needed to use the Pack URI Format. So,

<ResourceDictionary Source="pack://application:,,,/Styles/MetroTheme.xaml"/>

EDIT

Turns out the above will eliminate build error but still results in runtime error. I needed to include full assembly specification for complete resolution (even though all files are in same assembly):

<ResourceDictionary Source="pack://application:,,,/WpfApplication10;component/Styles/MetroTheme.xaml"/>

answered May 6, 2017 at 18:55

nmarler's user avatar

nmarlernmarler

1,4161 gold badge11 silver badges16 bronze badges

Make sure that the build action for MetroTheme.xaml is set to Page.

enter image description here

answered Jun 15, 2012 at 15:16

Andy's user avatar

AndyAndy

6,3361 gold badge32 silver badges37 bronze badges

1

Sometimes closing Visual Studio and open it again solves this problem.

answered Jun 5, 2019 at 21:57

Leonard Keret's user avatar

1

Change the target .net version to an older one in the project properties and then reset to the previous version.

answered May 30, 2018 at 14:27

ABDULLA TK's user avatar

I have a merged resource dictionary in App.xaml Main assembly, which combines various resource dictionaries from separate assemblies: Common and PresentationLayer.

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/Common;component/Themes/Button.xaml"/>
            <ResourceDictionary Source="/PresentationLayer;component/DataTemplates/AppointmentsDataTemplates.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

At run time the styles in the resource dictionaries are applied to the controls correctly. However, at design time the styles are not applied and Visual Studio 2012 keeps giving the following error:

An error occurred while finding the resource dictionary "/Common;component/Themes/Button.xaml".

And warning:

The resource "BannerButton" could not be resolved.

I came across this post but the problem persists despite Build Action set to Resource. Also, I did not have this problem when running under Visual Studio 2010 or Expression Blend 4. The Main assembly definitely holds a reference to the Common assembly and I haven’t changed the Pack URIs.

Студворк — интернет-сервис помощи студентам

В проекте использую файл ресурсов.

XML
1
2
3
4
5
6
7
8
9
10
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
    xmlns:local="clr-namespace:SH2.Model.Repairs"
    xmlns:converter="clr-namespace:SH2.Converters">
    <!-- Конвертеры -->
    <converter:TypeToVisibleConverter x:Key="TypeVisibleConverter" />
    <converter:TreeHierarchyConverter x:Key="HierarchyConverter" />
    <converter:ValueToStylePaneConverter x:Key="ValToStyleConverter"/>

Возникает ошибка «Имя TypeToVisibleConverter не существует в пространстве имен …», и так со всеми подключениями.
Код рабочий, т.к в другом проекте точь-в-точь такой же код и все работает.

XML
1
2
3
4
5
<ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/SH2;component/Resources.xaml"/>
            </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

Здесь выдается ошибка, что произошла ошибка при поиске словаря ресурсов, заменяя на другой проект (SH1) все находит, только нет ссылок на сборку другого проекта.
Подскажите, что я тут мог забыть указать?

Перейти к контенту

I have a merged resource dictionary in App.xaml Main assembly, which combines various resource dictionaries from separate assemblies: Common and PresentationLayer.

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/Common;component/Themes/Button.xaml"/>
            <ResourceDictionary Source="/PresentationLayer;component/DataTemplates/AppointmentsDataTemplates.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

At run time the styles in the resource dictionaries are applied to the controls correctly. However, at design time the styles are not applied and Visual Studio 2012 keeps giving the following error:

An error occurred while finding the resource dictionary "/Common;component/Themes/Button.xaml".

And warning:

The resource "BannerButton" could not be resolved.

I came across this post but the problem persists despite Build Action set to Resource. Also, I did not have this problem when running under Visual Studio 2010 or Expression Blend 4. The Main assembly definitely holds a reference to the Common assembly and I haven’t changed the Pack URIs.

I have a merged resource dictionary in App.xaml Main assembly, which combines various resource dictionaries from separate assemblies: Common and PresentationLayer.

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/Common;component/Themes/Button.xaml"/>
            <ResourceDictionary Source="/PresentationLayer;component/DataTemplates/AppointmentsDataTemplates.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

At run time the styles in the resource dictionaries are applied to the controls correctly. However, at design time the styles are not applied and Visual Studio 2012 keeps giving the following error:

An error occurred while finding the resource dictionary "/Common;component/Themes/Button.xaml".

And warning:

The resource "BannerButton" could not be resolved.

I came across this post but the problem persists despite Build Action set to Resource. Also, I did not have this problem when running under Visual Studio 2010 or Expression Blend 4. The Main assembly definitely holds a reference to the Common assembly and I haven’t changed the Pack URIs.

I’m in the process of building a WPF application and ran into an error when trying to reference a resource dictionary. Inside my WPF application project I have a folder called «Styles» to contain all the xaml style templates for my app:

VS2010 Solution Explorer

In my app.xaml file I have this:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Styles/MetroTheme.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

However, when I hover over the source property I get an error saying «An error occurred while finding the resource dictionary «Styles/MetroTheme.xaml». I can see the xaml file inside the folder both in Visual Studio and in the file system.

I have also tried «/Styles/MetroTheme.xaml» and a pack uri for the source property, both with no success. Any idea why I’m getting this file not found error?

asked Jun 15, 2012 at 15:09

Steven Ball's user avatar

1

Make sure that the build action for MetroTheme.xaml is set to Page.

enter image description here

answered Jun 15, 2012 at 15:16

Andy's user avatar

AndyAndy

6,2861 gold badge31 silver badges37 bronze badges

1

I had the same issue, but setting Build Action = Page did not solve for me. Turned out I needed to use the Pack URI Format. So,

<ResourceDictionary Source="pack://application:,,,/Styles/MetroTheme.xaml"/>

EDIT

Turns out the above will eliminate build error but still results in runtime error. I needed to include full assembly specification for complete resolution (even though all files are in same assembly):

<ResourceDictionary Source="pack://application:,,,/WpfApplication10;component/Styles/MetroTheme.xaml"/>

answered May 6, 2017 at 18:55

nmarler's user avatar

nmarlernmarler

1,3861 gold badge10 silver badges15 bronze badges

Sometimes closing Visual Studio and open it again solves this problem.

answered Jun 5, 2019 at 21:57

Leonard Keret's user avatar

1

Change the target .net version to an older one in the project properties and then reset to the previous version.

answered May 30, 2018 at 14:27

ABDULLA TK's user avatar

В проекте использую файл ресурсов.

XML
1
2
3
4
5
6
7
8
9
10
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
    xmlns:local="clr-namespace:SH2.Model.Repairs"
    xmlns:converter="clr-namespace:SH2.Converters">
    <!-- Конвертеры -->
    <converter:TypeToVisibleConverter x:Key="TypeVisibleConverter" />
    <converter:TreeHierarchyConverter x:Key="HierarchyConverter" />
    <converter:ValueToStylePaneConverter x:Key="ValToStyleConverter"/>

Возникает ошибка «Имя TypeToVisibleConverter не существует в пространстве имен …», и так со всеми подключениями.
Код рабочий, т.к в другом проекте точь-в-точь такой же код и все работает.

XML
1
2
3
4
5
<ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/SH2;component/Resources.xaml"/>
            </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

Здесь выдается ошибка, что произошла ошибка при поиске словаря ресурсов, заменяя на другой проект (SH1) все находит, только нет ссылок на сборку другого проекта.
Подскажите, что я тут мог забыть указать?

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

Team,

I have a simple wpf project in Visual Studio 2013. The structure is shown below. All that the error says is as shown in the title «An error occurred while finding the resource dictionary». I have tried many suggestions from the net and running out of patience. Every thing seems to be alright. Any one experienced with this can kindly suggest some thing. Thanks in advance.

VS 2013 Wpf Project Showing the error with respect to resources

asked Sep 8, 2014 at 9:39

VivekDev's user avatar

It should read:

...Source="/Skins/MainSkin.xaml"

As the skin isn’t in the Content directory.

At the moment it’s looking for Content/Skins/MainSkin.xaml (hence / will ‘take it up’ a directory back to the root).

answered Sep 8, 2014 at 9:41

2

Team,

I have a simple wpf project in Visual Studio 2013. The structure is shown below. All that the error says is as shown in the title «An error occurred while finding the resource dictionary». I have tried many suggestions from the net and running out of patience. Every thing seems to be alright. Any one experienced with this can kindly suggest some thing. Thanks in advance.

VS 2013 Wpf Project Showing the error with respect to resources

asked Sep 8, 2014 at 9:39

VivekDev's user avatar

It should read:

...Source="/Skins/MainSkin.xaml"

As the skin isn’t in the Content directory.

At the moment it’s looking for Content/Skins/MainSkin.xaml (hence / will ‘take it up’ a directory back to the root).

answered Sep 8, 2014 at 9:41

2

Я занимаюсь созданием приложения WPF и сталкивался с ошибкой при попытке ссылаться на словарь ресурсов. В моем проекте приложения WPF у меня есть папка под названием «Стили», которая содержит все шаблоны стиля xaml для моего приложения:

Изображение 349058

В моем файле app.xaml у меня есть это:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Styles/MetroTheme.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

Однако, когда я нахожусь над исходным свойством, я получаю сообщение об ошибке «Ошибка при поиске словаря ресурсов» Styles/MetroTheme.xaml «. Я вижу файл xaml внутри папки как в Visual Studio, так и в файловой системы.

Я также попробовал «/Styles/MetroTheme.xaml» и пакет uri для свойства source, оба без успеха. Любая идея, почему я получаю этот файл, не найдена ошибка?

15 июнь 2012, в 17:57

Поделиться

Источник

4 ответа

Убедитесь, что для действия сборки для MetroTheme.xaml установлено значение Страница.

Изображение 521852

Andy
15 июнь 2012, в 13:13

Поделиться

У меня была такая же проблема, но установка Build Action = Page не решила для меня. Оказалось, мне нужно было использовать Pack URI Format. Таким образом,

<ResourceDictionary Source="pack://application:,,,/Styles/MetroTheme.xaml"/>

ИЗМЕНИТЬ

Оказалось, что вышесказанное устраняет ошибку сборки, но все же приводит к ошибке выполнения. Мне нужно было включить полную спецификацию сборки для полного разрешения (даже если все файлы находятся в одной сборке):

<ResourceDictionary Source="pack://application:,,,/WpfApplication10;component/Styles/MetroTheme.xaml"/>

nmarler
06 май 2017, в 17:03

Поделиться

Иногда закрытие Visual Studio и открытие его снова решает эту проблему.

Leonard Keret
05 июнь 2019, в 20:36

Поделиться

Измените целевую версию .net на более старую в свойствах проекта, а затем сбросьте ее до предыдущей версии.

ABDULLA TK
30 май 2018, в 12:11

Поделиться

Ещё вопросы

  • 0CalDavClient добавить новую запись
  • 1Интеграция Twitter + OAuth
  • 1Ссылка на метод WTForms render_field () для переменных цикла
  • 0Часы в месяце — MySQL запрос
  • 0В чем разница между (char *) и char *?
  • 0Внедрить Сидр в Дюрандаль
  • 1Как заставить класс использовать метод получения / установки по умолчанию, когда на него ссылаются непосредственно в C #?
  • 1Являются ли объекты DSLContext тяжелыми в JOOQ?
  • 1Webpack, postcss и nanocss: как установить глобальную переменную для CSS
  • 0Почему ChangeWindowMessageFilter вызывает сбой Qt?
  • 0Сохранять содержимое формы при закрытии модального Ui-Bootstrap
  • 1Pipenv не удается установить какие-либо пакеты
  • 0как открыть TXT-файл с другого сервера с помощью PHP
  • 0Автоматическое обновление вкладки HTML в Internet Explorer
  • 1Какое событие сообщает мне, когда планшет разблокирован?
  • 0PHP зацикливание одного массива внутри другого
  • 0Spring — Как отобразить подменю во всех URL
  • 1Проблема с Android jAudioTagger — чтение mp3 файла — VerifyError
  • 0Кнопка не в состоянии выполнить функцию jQuery
  • 1Android, широкий или несколько экранов
  • 0Столбчатая диаграмма в Google Chart отображает панель ниже мин
  • 0по какой причине Window.location.href иногда не работает?
  • 0Как получить значение пользовательского атрибута с помощью jquery?
  • 1regex.test возвращает неожиданный результат
  • 1Как я могу определить, буду ли я рисовать за пределами экрана при выполнении пользовательского растрового растрескивания в представлении внутри прокрутки в Android
  • 0Выбор элементов по содержанию текста в jQuery
  • 0Выполнить команду, используя popen
  • 1_.bindAll не работает при визуализации представления Backbone
  • 1Как добавить информацию о вызывающем абоненте в трассировку стека ошибок в node.js?
  • 0Как я могу сделать чистый вызов javascript для node.js, который обновит панель мониторинга через websockets
  • 0php get_headers ничего не возвращает, пока страница существует
  • 0MySQL подсчет с ГДЕ и GROUP BY
  • 1Невозможно вызвать getApplicationContext () внутри потока
  • 0Отключить противоположный ввод, если я наберу в другой из пары
  • 0Пользовательские привязки Knockout и JQuery UI не распознают виджет при обновлении наблюдаемого массива
  • 0Почему Flask возвращает <embed> файлы для загрузки вместо их отображения
  • 1Отобразить массив двоичных комбинаций в массив двоичных индексов
  • 1Java это и супер ключевые слова
  • 0Ошибка: недопустимое значение для <path> attribute d = «.. для круговой диаграммы
  • 1Несколько обещаний JavaScript, приводящих к нулю
  • 1как реализовать приостановку обработчика для другого действия, выполняющего это действие
  • 0MySQL получает количество книг для каждого пользователя
  • 0Добавить текст в начале определенной строки в PHP
  • 1Python — Как я могу сделать этот повторяющийся код короче, используя цикл?
  • 0Не могу заставить мой алгоритм сжатия работать правильно
  • 1Java: ошибка вывода преобразования даты
  • 1C # Ожидание окончания делегата, прежде чем продолжить
  • 0тот же код, но другой дисплей
  • 0PHP — безопасный PDO подготовил оператор с неизвестным количеством параметров

Сообщество Overcoder

У меня есть объединенный словарь ресурсов в основной сборке App.xaml, который объединяет различные словари ресурсов из отдельных сборок: Common и PresentationLayer.

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/Common;component/Themes/Button.xaml"/>
            <ResourceDictionary Source="/PresentationLayer;component/DataTemplates/AppointmentsDataTemplates.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

Во время выполнения стили в словарях ресурсов правильно применяются к элементам управления. Однако во время разработки стили не применяются, и Visual Studio 2012 продолжает выдавать следующую ошибку:

An error occurred while finding the resource dictionary "/Common;component/Themes/Button.xaml".

И предупреждение:

The resource "BannerButton" could not be resolved.

Я наткнулся на этот пост, но проблема не устранена, несмотря на то, что для действия Build Action установлено значение Resource. Кроме того, у меня не было этой проблемы при работе в Visual Studio 2010 или Expression Blend 4. Основная сборка определенно содержит ссылку на общую сборку, и я не менял URI пакета.

Для VS2017, если имеется ссылка на сборку и двойная проверка правильности всех имен, попробуйте закрыть VS и удалить каталог .vs в каталоге решения. Это приведет к потере всех пользовательских настроек (запускаемый проект, масштабирование дизайнера WPF и т. Д.), Но это исправит.


8

rattler
29 Мар 2019 в 16:53

Если вы используете Visual Studio 2017, попробуйте перезагрузить компьютер. Проблема может быть решена.


2

Casper
19 Сен 2017 в 10:53

Попробуйте то же самое в Window.Resources, убедитесь, что вы добавили пространство имен при использовании app.xaml, и не забудьте изменить параметр build на page , где вам нужно это использовать. app.xaml.


1

Jaya shanmuga pandian
18 Янв 2013 в 09:47

У меня была такая же проблема, и причиной было неправильное написанное слово в xaml-файле словаря ресурсов. Проверьте xaml-файл словаря ресурсов на предмет неправильного написания и ошибок. После исправления орфографии все заработало.


0

Stefan27
20 Янв 2021 в 17:23

Я использую VS2019, получаю эту ошибку.

Я просто перезапускаю VS , и ошибка исчезла.


0

Even Wonder
5 Май 2021 в 16:12

В моем приложении есть определенные ошибки в окне ошибок во время разработки, связанные со словарем ресурсов. Например, в моем главном окне словарь ресурсов вызывается следующим образом;

<Window.Resources>
    <ResourceDictionary Source="Resources.xaml"/>
</Window.Resources>

Я получаю синюю линию в средней строке, говорящую: «Произошла ошибка при поиске словаря ресурсов «Resources.xaml». Тем не менее, Resources.xaml находится в корневой папке проекта, как и MainWindow.

Я знаю, что есть подобные вопросы, подобные этому, однако ответы;

«Убедитесь, что Resources.xaml настроен на создание действия: страница»

«Убедитесь, что вы правильно ссылаетесь на Resources.xaml»

не были мне полезны.

У меня есть дополнительная проблема в том, что в словаре ресурсов у меня есть ошибки, говорящие мне;

the name ProductDatabaseViewModel does not exist in the namespace "clr-namespace:gate2software.ViewModels"

и аналогично;

the name ProductDatabaseView does not exist in the namespace "clr-namespace:gate2software.Views"

в следующем xaml;

<DataTemplate DataType="{x:Type vm:ProductDatabaseViewModel}">
    <vw:ProductDatabaseView />
</DataTemplate>

На самом деле оба они доступны именно там, где они заявлены.

Буду очень признателен за любые предложения по любой из моих двух проблем.

У меня есть объединенный словарь ресурсов в основной сборке App.xaml, который объединяет различные словари ресурсов из отдельных сборок: Common и PresentationLayer.

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/Common;component/Themes/Button.xaml"/>
            <ResourceDictionary Source="/PresentationLayer;component/DataTemplates/AppointmentsDataTemplates.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

Во время выполнения стили в словарях ресурсов правильно применяются к элементам управления. Однако во время разработки стили не применяются, и Visual Studio 2012 продолжает выдавать следующую ошибку:

An error occurred while finding the resource dictionary "/Common;component/Themes/Button.xaml".

И предупреждение:

The resource "BannerButton" could not be resolved.

Я наткнулся на этот пост, но проблема не устранена, несмотря на то, что для действия Build Action установлено значение Resource. Кроме того, у меня не было этой проблемы при работе в Visual Studio 2010 или Expression Blend 4. Основная сборка определенно содержит ссылку на общую сборку, и я не менял URI пакета.

Для VS2017, если имеется ссылка на сборку и двойная проверка правильности всех имен, попробуйте закрыть VS и удалить каталог .vs в каталоге решения. Это приведет к потере всех пользовательских настроек (запускаемый проект, масштабирование дизайнера WPF и т. Д.), Но это исправит.


11

rattler
29 Мар 2019 в 16:53

Если вы используете Visual Studio 2017, попробуйте перезагрузить компьютер. Проблема может быть решена.


4

Casper
19 Сен 2017 в 10:53

Я использую VS2019, получаю эту ошибку.

Я просто перезапускаю VS , и ошибка исчезла.


3

Even Wonder
5 Май 2021 в 16:12

Попробуйте то же самое в Window.Resources, убедитесь, что вы добавили пространство имен при использовании app.xaml, и не забудьте изменить параметр build на page , где вам нужно это использовать. app.xaml.


1

Jaya shanmuga pandian
18 Янв 2013 в 09:47

У меня была такая же проблема, и причиной было неправильное написанное слово в xaml-файле словаря ресурсов. Проверьте xaml-файл словаря ресурсов на предмет неправильного написания и ошибок. После исправления орфографии все заработало.


1

Stefan27
20 Янв 2021 в 17:23

Понравилась статья? Поделить с друзьями:
  • Произошла ошибка при поиске обновлений код 80072efe
  • Произошла ошибка при поиске обновлений windows 7 80072efe
  • Произошла ошибка при настройке порта win 7
  • Произошла ошибка при настройке порта usb001
  • Произошла ошибка при копировании файлов 0001 0002