Unable to Resolve Resources - c#

I am using the MaterialDesign for XAML package in WPF. When I run my application, all styles and controls are rendered as expected. However in the XAML designer I have dozes of errors such as "The resource 'MaterialDesignFlatButton' could not be resolved." Example of a line that is throwing that error:
<Button Style="{StaticResource MaterialDesignFlatButton}" IsDefault="True" Margin="0 8 8 0" ...
My app.xaml contents is as follows:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.Blue.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.LightBlue.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
I have attempted the top solution proposed on The resource "x" could not be resolved. but that causes the project to fail to run (I believe I am not using the correct pathing when attempting to use the proposed "absolute pack URI"). So I have two questions at this point:
Is there a reason the resources would fail to resolve in the XAML designer given the way I have defined them in App.xaml (per the developer guide: https://github.com/MaterialDesignInXAML/MaterialDesignInXamlToolkit/wiki/Getting-Started)?
How can I find out the "absolute pack URI" to use for the source for my resource dictionaries?

In the past, I had problems like this.
The error causes are as follow.
1. Setup and setting config
About this, please check the github and material design homepage.
2. Build and Compiler problem
About this, users may set the "Platform Target" as "x64".
That can invoke errors because material designer tool use "x32" compiler, so please use "any cpu" or "x32".

I had this problem with the flat accent button, while every other button style worked. I added the resource for buttons, then the error was gone. Then I removed the button resource... and the error was still gone.
https://github.com/MaterialDesignInXAML/MaterialDesignInXamlToolkit/wiki/FAQ
Exception: Cannot find resource named 'MaterialDesign...'
This error typically comes when you have a static resource referencing
one of the material design styles, and have not included the
appropriate resource dictionary that contains the style. Try the
following:
Ensure that you have loaded all of the default material design styles in your App.xaml. You can find directions for this in the
Getting Started guide.
Ensure you have referenced the control specific resource dictionary that contains the style. The path for this is resource dictionary
should be .xaml" />. For example, if you were trying to reference the
MaterialDesignFloatingActionMiniButton style for a button, the
resource dictionary source would be: . Typically these inclusions are done at root of your Window, User
Control, or Template. You can find the full list of the resource
dictionaries here

Related

How to handle resource loading in a control that is packed into a nuget?

I'm working on a generic 'window control' as I find I do a lot of the same things in the desktop apps I work on. I have a small project with a control, designed to go in a window in another project. This worked fine when in different projects (but the same solution), but now I have moved the window control to a new solution and packed it into a nuget, then referenced the nuget in my project with the window.
On initialising the window, it complains it can't find a resource that the control uses. For theming, when the user sets a theme (and on startup) an image which will best suit the brightness of the theme colour is picked and applied to a UI bound BitmapImage property. This is the resource that the usage of the control in my window in another project can't find, I get this error:
To me it seems the application I am using the control in is trying to find the pngs in its own resources, rather than that of the nuget. But I'm unsure on how to ensure the nuget functions only internally.
The two images to pick from are both set as 'Resource' and not to copy to output. I have also tried solutions where the images are simply copied to the output and read in via a relative path, however this doesn't seem to work:
On setting the theme, this code runs:
ThemeImage = isThemeDark
? new BitmapImage(new Uri(#"pack://application:,,,/Images/Pallete_Light.png", UriKind.Absolute))
: new BitmapImage(new Uri(#"pack://application:,,,/Images/Pallete_Dark.png", UriKind.Absolute));
This works fine on a test window in the same project as the control, the little colour pallete icon is the on being picked from:
My window is very simple, and is the same as the window from the project where it works.
<Window
x:Class="SomeApplicationName.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SomeApplicationName" xmlns:win10themables="clr-namespace:Win10Themables;assembly=Win10Themables"
Title="SomeApplicationName"
Width="800"
Height="450"
AllowsTransparency="True"
Background="Transparent"
ResizeMode="NoResize"
WindowStyle="None"
WindowState="{Binding ElementName=WindowControl, Path=DataContext.WindowStateProperty, UpdateSourceTrigger=PropertyChanged}">
<win10themables:MainWindowControl x:Name="WindowControl" Title="SomeApplicationName" />
</Window>
In my App.xaml, I simply merge some resource dictionaries from the project the window control comes from so this project can use them:
<Application
x:Class="SomeApplicationName.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Win10Themables;component/ResourceDictionaries/Styles.xaml" />
<ResourceDictionary Source="/Win10Themables;component/ResourceDictionaries/Converters.xaml" />
<ResourceDictionary Source="/Win10Themables;component/ResourceDictionaries/Brushes.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
Sorry for the code dump. I'm at a bit of a loss on how to resolve this. I wanted to avoid repeatedly copying the base window project into each of my new projects, but at this point might be forced to do so anyway.
To anyone else who runs into this issue, I resolved this by keeping the images as resources, but then adding the images to a resource dictionary and merging that into the app.xaml of the project with the control, and referencing the image through Application.Current.Resource["ImageResourceName"] and casting to the type of my property (BitmapImage).
In my application where I consume this nuget (and add the control to the window), I also merge this resource dictionary into my app.xaml. This seems to resolve the issue, though I can't entirely understand the difference between referring it via the projects resources, and the resource dictionary, and why the latter resolves this. If anyone viewing this with this answer has any light to shed on this for mine and anyone elses benefit, please do!

ResourceDictionary.MergedDictionaries causes weird errors

Inside my WPF Application I am including a ResourceDictionary from another Project.
<Application x:Class="namespace.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<!-- This Line causes an Error -->
<ResourceDictionary Source="pack://application:,,,/Commons;Component/Generic.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
Metadata override and base metadata must be of the same type or derived type.
The solution builds successful and runs.
Restarting Visual Studio doesn't fix it.
Cut and Paste the <ResourceDictionary Source="..." /> line causes another error as explained here in the Comments:
Value Cannot be Null. Parameter Name: item. Restarting Visual Studio will then bring back the old error.
Sadly I haven't found out how to reproduce this error, I can only tell you something more about the environment im using:
Visual Studio 2015 Professional, Version 14.0.25431.01 Update 3
And allthough I doubt, those are associated with my problem, here my installed Plugins:
Resharper Ultimate 2017.1.1
GitExtensions Version 2.49.03
Sinatr's comment hinted me to read more about theming.
ThemeInfo
Inside of a Custom Control Library theres automatically created a ThemeInfoAttribute inside AssemblyInfo.cs
[assembly:ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
Parameters
As it states in the autogenerated comments, the first parameter is to determine wheter there exist or where to find Theme specific resource dictionaries.
The second parameter defines wheter there exist or where to find the generic ResourceDictionary (Generic.xaml).
ResourceDictionaryLocation-Enumeration
The ResourceDictionaryLocation-Enumeration itself is used to specify the location of those dictionaries.
ResourceDictionaryLocation.None
No theme dictionaries exist.
ResourceDictionaryLocation.SourceAssembly
Theme dictionaries exist in the assembly that defines the types being themed.
This expects the ResourceDictionary to be located in a /Themes-Folder. Explanation later.
ResourceDictionaryLocation.ExternalAssembly
Theme dictionaries exist in assemblies external to the one defining the types being themed.
I am not going to explain how this works.
Why /Themes-Folder
Sadly I couldn't find too much about this. If someone has some more info please share.
Have you ever wondered, how styles of a lookless control are being applied?
If one created a lookless Control, he did as follows:
public class MyControl : ControlTemplate
{
static MyControl()
{
// This tells WPF to search for a Style for this type
DefaultStyleKeyProperty.OverrideMetadata(typeof(MyControl)),
new FrameworkPropertyMetadata(typeof(MyControl)));
}
}
In short, Ressources in WPF are located, by searching up the Logical-Tree, then inside Application's Resources and finally inside sth. they call System-Area (this is my translation from German, if you know a better one pls tell).
So depending on ThemeInfo, MyControl propably had its Style inside a ResourceDictionary inside the /Themes-Folder, eg. /Themes/Generic.xaml. And that tells WPF to add the Ressources to the System-Area which finally results in automatically resolving the appropriate style.
Somewhere inside /Themes/Generic.xaml:
<Style TargetType="{x:Type MyControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type MyControl}">
..
</ControlTemplate/>
</Setter.Value>
</Setter>
</Style>
That's why the above ThemeInfoAttribute requires Generic.xaml to be located in a /Themes-Folder. - And somehow, even if in my case the System-Area-Functionality isn't even used for this generic file, this causes those errors. But I wasn't able to find out why.
Sources:
ThemeInfoAttribute Constructor
ResourceDictionaryLocation Enumeration
Windows Presentation Foundation - Das Umfassende Handbuch, Rheinwerk Computing Version 4

WPF MergedDictionaries - Value Cannot be Null - Parameter Name: item

I am having a nagging issue with my App.Resources MergedDictionary. Every time add a new dictionary with a source and XML namespace from another assembly, an error is produced and I cannot build my program.
The error appears in App.xaml with the ResourceDictionary underlined and the message Value Cannot be Null. Parameter Name: item. This makes absolutely no sense as I have done the exact same thing before. The only difference is that this time, I am referencing the namespace of another assembly(c# class library). Here is the App.xaml file:
<Application x:Class="Quiz.Client.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Quiz.Client"
StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Resources/Styles.xaml" />
<ResourceDictionary Source="Resources/Templates.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
Below is Styles.xaml:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Quiz.Client">
<Style x:Key="StrongFont"
TargetType="ContentControl">
<Setter Property="FontSize"
Value="20" />
<Setter Property="FontWeight"
Value="ExtraBold" />
<Setter Property="Foreground"
Value="DarkRed" />
</Style>
</ResourceDictionary>
Here is Templates.xaml:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Quiz.Client"
xmlns:domain="clr-namespace:Quiz.Core.Domain;assembly=Quiz.Core"
xmlns:common="clr-namespace:Quiz.Client.Common">
<DataTemplate x:Key="ArithmeticQuestionTemplate"
DataType="domain:ArithmeticQuestion">
</DataTemplate>
<common:QuestionTemplateSelector x:Key="QuestionTemplateSelector"
ArithmeticTemplate="{StaticResource ArithmeticQuestionTemplate}" />
</ResourceDictionary>
What the heck is going on? Was there a software-breaking change introduced or something? I am completely lost.
Confirm!!! This bug is tracked by Microsoft. This mean WPF in some points will is trying to report to Microsoft automatically with Microsoft report process. During the report VS start freeze. Please, wait bug report to finish.
The bug still exist in lattes VS 2019.
After restart everything is fine. Confirm!!!
Thanks for the answer. I believe it is a Visual Studio bug caused by something unknown. Maybe one of my plugins, who knows. The only thing that fixes the issue is restarting visual studio and building the project. The problem seems to begin when adding a new namespace from another assembly. The project then can't build until visual studio is restarted. Very weird, never seen anything like it before. – user3096803
Not sure why your method isn't working but it's not how I usually import resources myself. Typically I'll add a ResourceDictionary to my library project, put all the libraries resources in that and import it into my main project using pack syntax:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MyLibrary;component/LibraryResources.xaml" />
</ResourceDictionary.MergedDictionaries>
<!-- main project resources go here -->
</ResourceDictionary>
In general I'd argue that this is a better architecture anyway as it doesn't require a re-compile of your main project each time one of the child library resources change. It also makes it easier later on if you decide to switch to MEF, as your library resources are now encapsulated in a single ResourceDictionary object that you can readily [Export].
I don't really understand the answer from #Pit but I tried restarting visual studios and also changing all source paths to full pack URIs, and nothing seemed to work. Came across this thread that hinted at using Tools > Options > Preview Features > New WPF XAML Designer for .NET Framework which fixed the issue for me.
EDIT: This "fix" may have been a red herring, it still had issues but they were equally cryptic! After switching back to the old XAML designer and doing some further digging I found that one of my merged dictionaries was incompatible with the wpf designer and it was resulting in this error. The fix on that page resolved my issue.
This specific fix probably won't help anyone, but hopefully the methodology will. Check if there are any errors in any of the individual resource dictionaries in the merged dictionaries.

Error Occurred Loading Resource Dictionary

I've looked at and tried these other solutions that I've found, and even copied Telerik's Documentation. However, I still can't get a working solution.
XAML:
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="NotifyIconResources.xaml" />
<ResourceDictionary Source="pack://application:,,,/Telerik.Windows.Themes.Windows8;component/Themes/System.Windows.xaml" />
<ResourceDictionary Source="pack://application:,,,/Telerik.Windows.Themes.Windows8;component/Themes/Telerik.Windows.Controls.xaml" />
<ResourceDictionary Source="pack://application:,,,/Telerik.Windows.Themes.Windows8;component/Themes/Telerik.Windows.Controls.Navigation.xaml" />
</ResourceDictionary.MergedDictionaries>
Here is an image of the error that ReSharper is giving:
Here's an image of the assembly being a reference:
Here's an image of the assembly properties:
Lastly, here's the exception information when I try to run the app:
System.Windows.Markup.XamlParseException was unhandled
HResult=-2146233087
Message='Cannot create unknown type '{clr-namespace:Telerik.Windows.Controls.External}Windows8ThemeExternal'.' Line number '15' and line position '6'.
Source=PresentationFramework
LineNumber=15
LinePosition=6
StackTrace:
at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
at MyApp.App.InitializeComponent() in App.xaml: line 1
at MyApp.App.Main() in c:\MyApp\obj\Debug\App.g.cs: line 0
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.Xaml.XamlObjectWriterException
HResult=-2146233088
Message='Cannot create unknown type '{clr-namespace:Telerik.Windows.Controls.External}Windows8ThemeExternal'.' Line number '15' and line position '6'.
Source=System.Xaml
LineNumber=15
LinePosition=6
StackTrace:
at System.Xaml.XamlObjectWriter.WriteStartObject(XamlType xamlType)
at System.Xaml.XamlWriter.WriteNode(XamlReader reader)
at System.Windows.Markup.WpfXamlLoader.TransformNodes(XamlReader xamlReader, XamlObjectWriter xamlWriter, Boolean onlyLoadOneNode, Boolean skipJournaledProperties, Boolean shouldPassLineNumberInfo, IXamlLineInfo xamlLineInfo, IXamlLineInfoConsumer xamlLineInfoConsumer, XamlContextStack`1 stack, IStyleConnector styleConnector)
at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
InnerException:
The first thing that I know IS wrong and that has to be added, according to Telerik documentation,
They can be merged in the resources of your application (in App.xaml) and as a result will be applied implicitly on any control that does not have a local Style set. For example, if you need to style a control from Telerik.Windows.Controls.dll, you need the Telerik.Windows.Controls.xaml resource dictionary.
That being said you're missing a ResourceDictionary for DataVisualization. If that doesn't solve the problem, keep reading.
Last I recall, when I was looking at theme'ing my application using Telerik, there are a couple different ways you can apply styles, and doing it right might be a little tricky at first. There is Implicit Styling (NoXaml) and there is standard styling, where styles are built into the control libraries. Implicit styling is the recommended approach for styling your application in a "global" manner. IIRC, it is also more performant is much more clean in code.
Since we talked in the WPF chat, it sounds like you weren't sure which binaries you were trying to build from source. Implicit styles requires you to build the Binaries.NoXaml source code. After that's said and done, you have to make sure you're adding references to the correct assemblies coming from the ..\Binaries.NoXaml\WPF4x\ directory.
The last time I built from source, the build instructions were included inside the downloaded .ZIP. Make sure you follow those instructions carefully. I have no used built in Visual Studio Telerik tools to build/deploy my referenced libraries, so if you are, then maybe manual is the way to go.
A couple other things. I'm suspicious the build wasn't successfully completed. Your Version # on your Telerik references should be something other than 0.0.0.0. Secondly, if I remember correctly, I had problems with defining the source and possibly the order matters--so try the source that I used in my example below, and maybe move the NotifyIconResources.xaml below the Telerik declarations.
Here is my XAML used with implicit style technique:
<ResourceDictionary Source="/Telerik.Windows.Themes.Windows7;component/Themes/Telerik.Windows.Controls.xaml" />
<ResourceDictionary Source="/Telerik.Windows.Themes.Windows7;component/Themes/System.Windows.xaml" />
<ResourceDictionary Source="/Telerik.Windows.Themes.Windows7;component/Themes/Telerik.Windows.Controls.Input.xaml" />
<ResourceDictionary Source="/Telerik.Windows.Themes.Windows7;component/Themes/Telerik.Windows.Controls.Navigation.xaml" />
As always, starting a new project and getting a basic thing like this working might do you wonders and it will also prevent you from changing so many things in your current code base that you end up forgetting the things you've changed and causing issues in places you don't want them.

ResourceDictionary with MVVM and Prism

I have set up a Prism project with one module. In the module I have defined some views. I want to use a ResourceDictionary to style UI elements.
However...if I include the following code in the View1.xaml
i get the following error
Warning 1 The designer does not support loading dictionaries that mix 'ResourceDictionary' items without a key and other items in the same collection. Please ensure that the 'Resources' property does not contain 'ResourceDictionary' items without a key, or that the 'ResourceDictionary' item is the only element in the collection.
Here is the code:
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="../Resources/ResourceDictionary.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
If I include the code in the App.xaml file the style looks applied in the designer, but when I run the project i get the following error:
Cannot find a Resource with the Name/Key
Do you have any useful advices how to use ResourceDictionary styles with Prism and MVVM?
Thanks
Maybe this guy here had a similar problem:
http://blog.caraulean.com/2011/09/13/how-to-make-caliburn-micro-and-silverlight-resources-in-mergeddictionaries-play-nicely-together/
Have a check

Categories

Resources