If I create a new project in Visual Studio 2010 SP1 and select "WPF Application" and tries to build the generated application, I get the error
The name 'InitializeComponent' does not exist in the current context.
I got a similar error this morning when I tried to build my current project. Yesterday, I had no problem compiling and running it.
I created a new project and got the error whenever I compiled the project. I have just sent the project to a colleague, and he has just compiled without any errors.
What is wrong?
I've encountered this a couple times and keep forgetting what causes it.
I ran into this when I renamed the namespace on my code behind file but not in my XAML.
So check if you've done the same.
The namespace and class names need to match since they are both part of a partial class
namespace ZZZ
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow
{
//...
}
}
<!-- XAML -->
<Window x:Class="ZZZ.MainWindow">
The Build Action for the .xaml file must also be set to "Page", when moving a xaml file between projects this setting gets lost (in VS 2010 at least).
For those who have no errors in Debug mode, but do have the specified error in Release mode (and yet the project runs fine), here is something simple to try:
Open the XAML file corresponding to the offending xaml.cs file.
Make an edit--any edit, like add a space somewhere
Save the file and close it
This method worked for me in VS 2015, and according to other users, also 2017 and 2019
Navigate to the solution directory
Delete the \obj folder
Rebuild the solution
I encountered this error during refactoring where I renamed some files/folders and the pre-existing *.g.cs files needed to be regenerated.
There's a very specific reason for this, and it's in the project settings. This usually happens whenever you try to add a WPF control/window to a .NET 2.0 class library or project. The reason for this error is that the project does not know it's building a WPF control or window and therefore tries to build it as a C# 2.0 project.
The solution involves editing the .csproj file. Right click on the project causing the problem and select “Unload Project”. Right click the unloaded project and select “Edit .csproj”. The .csproj file will open and you can see the XML. look for the following line:
<Import Project=…..
It's near the end of the file, and the only line that you have is probably
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
This tells Visual Studio to build the project as a .NET 2.0 project. What we want to do is to tell Visual Studio that this is actually a WPF project, so we have to add the following line:
<Import Project="$(MSBuildBinPath)\Microsoft.WinFX.targets" />
This line will tell Visual Studio to build the project as a WPF project. Now your .csproj file bottom should look like this:
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="$(MSBuildBinPath)\Microsoft.WinFX.targets" />
Save the .csproj file, right click it in Solution Explorer and select “Reload Project” compile and that's it, you're all done!
this happened with me when I accidentaly deleted the class reference from the xaml definition:
I've replaced the
<Window x:Class="myapp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
first line with this:
<RibbonWindow
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
I know this isn't the answer to the original question (because thats project builds on another machine), but the error message was the same, so maybe I'll help someone with this situation.
None of the above answers worked for me. I tried them all except the duplicate ones. However for some weird reason this worked in my cross-platform project in Visual Studio 2015:
Right-click the project that is causing the problem in the Solution Explorer. In the pop-up menu choose: Add --> Class
Select cross-platform --> Forms Xaml Page. Keep the pretty Page1.cs standard name and click Add.
Notice how the previous InitializeComponent()-problem just disappeared for some reason.
Delete the newly created Page1.cs and continue programming as if Visual Studio was working just fine.
You might get this error when you import a class from another project, or change the path of the xaml file, or the namespace of either the xaml or behind .cs file.
One: It might have a namespace that is not the same as what you have in you new project
namespace TrainerB.MVC.Forms
{
public partial class AboutDeveloper : ContentPage
{
public AboutDeveloper()
{
InitializeComponent();
}
}
}
As you can see the name space in the imported file begins with the old project name: "TrainerB", but your new project might have a different name, so just change it to the correct new project name, in both the .xaml file and the behind .cs file.
Two:
change the properties of the .xaml file to:
Build Action: Embedded Resource
Custom Tool: MSBuild:UpdateDesignTimeXaml
Check the Designer file.
I had this same issue. In my case, the cause was that the namespace for FileName.Designer.cs did not match the (correct) namespace used in FileName.cs.
Changing the namespace of FileName.Designer.cs to match that of FileName.cs solved the problem immediately.
I've had this (although it was very much my fault and was caused after I copied and pasted some code in); it can occur when the namespace doesn't match between the XAML and code behind
EG
<UserControl x:Class="DockPanel.TreeView" />
and the code behind is
namespace NotDockPanel
I encountered this while renaming a usercontrol. The way I fixed it was to comment out InitializeComponent, verify that all the names were correct (xaml and code behind), build the project, uncomment InitializeComponent, then build again. It sounds like there may be a couple causes/solutions for this issue, but this way did it for me.
I agree with the answer above that the namespaces have to match. However, I had a problem like this where the namespaces matched.
To fix, I simply changed the namespace in the XAML to an INCORRECT one, saved, then changed it back to the CORRECT one. Voila!
Unload the entire solution and then reload it again. Then Rebuild the solution. This resolved the issue for me.
What helped me - is to change first line in .csproj to
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
I try all suggestions above. If you try too without success get the more easy way. Create a new page.xaml then copy your code for new class and delete class XAML with problems. Don't spend more time.
If you are using Xamarin Forms and you move a XAML file the "build action" of the file is changed. Xamarin Forms requires "build action = Embedded Resource".
Apply "build action" in Visual Studio:
Select the XAML file -> Properties -> Build Action = Embedded Resource
Another solution to this problem is to simply change the property-> Build Action on the XAML from Embedded Resource to anything else, save, then change it right back to Embedded Resource. The error goes away.
Another common cause of this error is if you did something in this:
Right click on folder in project to create new UserControl. This creates a class and xaml file that derives from user control in the namespace of the folder.
Then you decide to change the namespace of the class because you're really just using folders for organization of code. The x:Class attribute will not get automatically updated so it will be searching for a class that doesn't exist. Could probably use a better error message like "x:Class type could not be found in namesace bla.blaa.blaaa."
If the Namespaces are correct then also there is a same error,
Just close your application and open it again.
This may solve your problem
This happened to me because a Nuget package uninstaller blew away all the attributes on the <Application> element in App.xaml. This included the x:Class attribute, which specifies the application class name. So the partial class containing the InitializeComponent() method was never generated.
I fixed the problem by reverting App.xaml to the source-controlled copy.
I have discovered that the "Startup object" was (Not set) causing this error for me.
"Startup object" (Not set)
I know this was answered due to a different cause, but this is a highly hit posting and I had ran into the same issue with a class library. In this case, it turned out to be both a change in my namespace (answered in this post here) and that the compiler could not rebuild the Window.g.i.cs which defines the InitializeComponent() method. It couldn't because the class library was missing the ProjectTypeGuid value for WPF projects in the csproj file. Instructions for this are here and here. I thought I would share in case someone else has run into the same issue. Just changing the namespace isn't enough in this case.
This solved it for me.
I had commented out the resources in the App.xaml file
<Application x:Class="MyApp.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Application.Resources>
<!--<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary
Source="/PresentationFramework.Aero, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, ProcessorArchitecture=MSIL;component/themes/aero.normalcolor.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>-->
</Application.Resources>
</Application>
Commenting thiis back in to fixed the build error.
<Application x:Class="MyApp.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary
Source="/PresentationFramework.Aero, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, ProcessorArchitecture=MSIL;component/themes/aero.normalcolor.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
Digging a bit deeper I found that the app.g.cs file in {Project}\obj\debug only contained the following when I left the resource commented in.
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Uri resourceLocater = new System.Uri("/MyApp;component/app.xaml", System.UriKind.Relative);
#line 1 "..\..\..\App.xaml"
System.Windows.Application.LoadComponent(this, resourceLocater);
#line default
#line hidden
}
For those who find this on the internet. Check the Windows.csproj file if the compilation is there. There should be 2 entries
<Page Include="YourFile.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Compile Include="YourFile.xaml.cs">
<DependentUpon>YourFile.xaml</DependentUpon>
</Compile>
After some action the namespace of the .cs file and the one in .xaml file may be different (in xaml look for the x:Class="namespace.yourType").
Fix them to be the same.
This issue happened for me when creating a "WPF Application Project" then changing its build target to "Class Library" to be used as an external tool by another program.
I changed all my .xaml files for my windows so their build action were set to "Page". What I did not realize was that that the project also contained "App.xaml" and "App.xaml.cs".
"App.xaml" needs to be set to "Page" as well, or deleted altogether (along with "App.xaml.cs"). I did the former, then the latter as I realized the files were useless.
Since this seems to be the go-to thread for the problem regarding missing 'InitializeComponent', I'll include my answer here.
I too was having this issue and I've tried everything I found here and in all other Forums that Google could find, however none resolved the issue for me. After two hours of trying everything, I finally figured out what was wrong with my setup.
In our project, we are using Metro components from MahApps. The view that was giving me trouble was a view inheriting from MetroWindow, like this:
<Controls:MetroWindow x:Class="ProjectNamespace.MyView"
xmlns:Controls="http://metro.mahapps.com/winfx/xaml/controls"
... >
Now, I have defined my static resources as
<Controls:MetroWindow.Resources>
<prop:Resources x:Key="LocalizedStrings"/>
...
</Controls:MetroWindow.Resources>
That's how I've defined Resources in UserControls in all my other views, so that's what I assumed will work.
That was, however, not the case with Controls:MetroWindow! There I absolutely needed the resource definition as follows:
<Controls:MetroWindow.Resources>
<ResourceDictionary>
<prop:Resources x:Key="LocalizedStrings"/>
...
</ResourceDictionary>
</Controls:MetroWindow.Resources>
So my issue, in summary, was a missing <ResourceDictionary> tag. I really don't know why this produced the 'InitializeComponent' error and it weirdly didn't even produce it on every machine of mine, but that's how I fixed it. Hope this helps (the remaining 0.001% of people encountering this issue).
I just encountered this problem, and it turned out to be that my project is stored in my user folder, which is stored on the network, and we had a momentary network outage. I did a build; it complained that my files had been modified outside the editor (they hadn't; the file locks just got borked), and it built fine, removing the error regarding the InitializeComponent() method.
BTW, in case you're wondering, developing something from a network drive is bad practice. It becomes particularly problematic when you're trying to leverage .NET's managed code; in my experience, it freaks out every time you build. I forgot to put this little throw-away project in the proper folder, and ended up paying the price.
Another possible explanation is that you're building against x86. Right-click your Solution and choose Configuration Manager. See if you're building against x86 instead of Any CPU.
So I realize this is an older question, but we were having a similar issue. We were able to build a project using VS2012, but not using msbuild from the command line. I went into the .proj file and noticed it didn't have a record for "ProjectTypeGuids" under the default "PropertyGroup" section, so I added this:
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
which is the project GUID for WPF. I then deleted and re-added the UserControl and it started working. I'm not sure if I had to do that last step, but it works for me now.
Related
I have an issue that is driving me nuts. When I try to build my VB.NET + WPF project in Visual Studio, I get an error "Type 'MyProject.MyUC' is not defined". This error appeared after I made some changes to other files from this solution (completely unrelated to that UC, it's backend code, or the window that uses that UC. Entirely separate code). I am using GIT, and I'm comparing old branch with a new branch, so I know this for a fact.
The window that uses the control is defined like this:
<Window x:Class="MyWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:uc="clr-namespace:MyProject"
xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
mc:Ignorable="d"
Title="MyWindow" Height="350" Width="650">
<Grid>
<uc:MyUC x:Name="MyUC"></uc:MyUC>
</Grid>
</Window>
The UC is defined like this:
<UserControl x:Class="MyUC"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:FLOATSOFT"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="600">
<Grid>
</Grid>
</UserControl>
And it's backed VB code:
Public Class MyUC
End Class
(No specific namespace declarations)
I have removed all functional code to show the structure. But even if I actually trim down my code to what I quoted, it doesn't compile.
I don't get it. MyUC is definitely in the MyProject namespace. If I hover my mouse over the class name in VB code, the tooltip says: "Class MyProject.MyUC", confirming it is definitely in the right namespace.
Why could this be happening? I still have all this that I quoted here in another GIT branch, and even though all these files match 100%, that other branch compiles, while this one gives this dreaded "Type 'MyProject.MyUC' is not defined" error.
I have tried:
Restarting Visual Studio - this used to help with such errors befoe;
Cleaning and rebuilding;
Re-creating all these files (MyWindow.XAML, MyWindow.XAML.VB, MyUC.XAML and MyUC.XAML.VB) and copying code to these new files;
Making sure my code builds if I comment out the usage of this UC and that there are no other compile errors.
Explicitly stating the namespace in the MyUC.XAML:
<UserControl x:Class="MyProject.MyUC"
And in MyUC.XAML.VB:
Namespace MyProject
Public Class MyUC
End Class
End Namespace
Doesn't help either. Same error.
Creating a new project and copying over these 4 files. It compiles. But it would be ridiculous having to re-create the project every time this happens. Like I said, it happens often, but restarting Visual Studio used to help. Not this time.
And I am at complete loss. I have reviewed dozens of similar posts to this one, but haven't found the answer. One answer suggested that this might be due to different .NET versions of the project and referenced assemblies, but I don't have any of that.
One branch compiles, another one throws this error. Both have identical code in every file that could possibly be related to this UC. How do I find the cause?
EDIT: I forgot to mention that I also tried creating a new UC from scratch in this project branch, and if I try to use it like this MyUC, this project branch won't compile. But the other branch still compiles.
EDIT: VERY IMPORTANT: I just discovered that if I change
<Grid>
<uc:MyUC x:Name="MyUC"></uc:MyUC>
</Grid>
To
<Grid>
<uc:MyUC></uc:MyUC>
</Grid>
(Omitting x:Name="MyUC"), then suddenly code compiles and I get no error. If I set a name to this UC - any name whatsoever - it won't compile. I have absolutely no idea what is happening.
I finally figured it out. Turns out, this issue is identical to this one. In short, I was right - nothing was changed in these 4 files, and they should have compiled. However, in a completely separate file, I incorrectly defined a namespace for one of the modules. I should have written:
Namespace MyModule
Public Module MyModule
End Class
End Namespace
But instead, I wrote:
Namespace MyProject.MyModule
Public Module MyModule
End Class
End Namespace
And although this MyModule is absolutely unrelated to the MyUC or MyWindow, apparently it created a namespace MyProject.MyProject, and that is why MyWindow wouldn't compile, as it tried to search for MyUC in MyProject.MyProject, presumably. Which is very weird, because the error I got did not suggest this. In fact, nothing anywhere ever suggested that I have this kind of namespace. Like I wrote in my question, everywhere I debugged, I found that MyUC has is declared directly in MyProject.MyUC. And every other window had the same declaration, yet they compiled.
I must admit that the error thrown by VS compiler was extremely unintuitive and the information it provided on namespaces was completely wrong for that UC, and I discovered the solution simply by accident. Even the Object Viewer showed that there is no issue with namespaces (it didn't show that I have MyProject.MyProject).
Hope this helps if anyone encounters the same issue. And I would also love to hear any suggestions on how to make these compiler errors more straightforward to the actual issue, because in this instance it was just plain wrong.
I have a WPF window and am using the MVVM pattern. I set the view model as a resource for the window as follows...
<Window
...other stuff removed for clarity...
xmlns:mvvm="clr-namespace:VisionRT.CRM.WPF.ViewModels.VRTSystems"
>
<Window.Resources>
<mvvm:DhrTemplatesViewModel x:Key="viewmodel" />
</Window.Resources>
I want to set the window's data context to use the resource, and found that the following XAML works...
<Window.DataContext>
<StaticResource ResourceKey="viewmodel"/>
<Window.DataContext>
The problem is that I can only do this by typing the XAML manually, Visual Studio doesn't show the resource anywhere. I can go to the window's properties and click the little icon next to the DataContext property, click the "Apply resource" option, but it doesn't show "viewmodel" as a resource, static or dynamic. If I enter the XAML manually and then open the "Apply resource" pop-up window, it has the "viewmodel" underlined as an error, and hovering over it shows a tooltip "cannot resolve resource reference"
However, when I run the application, it works fine, so the resource is being resolved at run time.
Anyone able to explain this? I would really like to be able to do this through the VS property editor, as I find that more convenient than typing the XAMl by hand. I'm also bothered by the fact that VS can't resolve it. This makes me think I'm doing something wrong.
Thanks for any explanation you can give.
The only (sad) explanation is that XAML is a second grade citizen in Visual Studio. Once you start pushing XAML a little more than basic and you end up with "unresolved" "cant display" "sorry I'm dumb", etc.
Refer to this WPF suggestion: http://dotnet.uservoice.com/forums/40583-wpf-feature-suggestions/suggestions/480899-make-xaml-a-first-class-citizen-of-visual-studio?ref=title to get them fixed.
It is possible to make Intellisense work 100% for a XAML {StaticResource} in Visual Studio.
Tested On
WPF/C#
Visual Studio 2015 Update 3
Step 1: Shift resources into shared project
The key is to shift all resources referenced by ResourceDictionary into a shared project:
Step 2: Design time intellisense
We're not quite there yet. The XAML runtime throws runtime if you include resources twice.
If we are including an .xaml file more than once in the entire project, we can include it at design time, but not at runtime:
public class DesignTimeResourceDictionary : ResourceDictionary
{
private Uri source;
public new Uri Source
{
get
{
if ((bool)DesignerProperties.IsInDesignModeProperty.GetMetadata(typeof(DependencyObject)).DefaultValue)
{
return null;
}
return this.source;
}
set { this.source = value; }
}
}
Then we can add design time resources:
<!--Design time resource dictionary, so intellisense will work with with {StaticResource}.-->
<ResourceDictionary.MergedDictionaries>
<dr:DesignTimeResourceDictionary Source="/Project.Name;component/Folder/SharedResourceA.xaml" />
<dr:DesignTimeResourceDictionary Source="/Project.Name;component/Folder/SharedResourceB.xaml" />
</ResourceDictionary.MergedDictionaries>
If we are using ReSharper, it will offer to automatically add the namespace prefix into the header:
xmlns:dr="clr-namespace:MyNamespace;assembly=Project.Name"
Appendix A: Extra for Experts: Why the need for Step 1?
As an aside, Intellisense in XAML is the same as Intellisense in C#: it only works with sub-projects that are referenced. This is why if projects A and B want to share some code, you must put it in a class library C that is referenced by projects A and B. This is in contrast to C or C++ where #including a file in the root makes it available to all subfiles.
With XAML, you can cheat and add static resources into Main Application Project (above), and the XAML runtime will still work properly - but Intellisense won't work at design time, presumably as its based on the same engine that is used for C# intellisense.
To make Intellisense work all the time in XAML, Visual Studio Intellisense would have to scan up through every parent project (instead of just down towards referenced projects).
For some reason the following code is giving me an exception.
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/PPCa.Common.Infrastructure;component/Skins/Default.xaml"/>
<ResourceDictionary>
<app:ResourceWrapper x:Key="ResourceWrapper" />
<app:NotOperatorValueConverter x:Key="NotOperatorValueConverter" />
</ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
Here is the exception:
System.Windows.Markup.XamlParseException occurred
Message=Failed to assign to property 'System.Windows.ResourceDictionary.Source'. [Line: 11 Position: 44]
LineNumber=11
LinePosition=44
StackTrace:
at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
InnerException:
Line 11 is this:
<ResourceDictionary Source="/PPCa.Common.Infrastructure;component/Skins/Default.xaml"/>
Am I somehow merging my dictionaries wrongly?
Why is no one answering my questions? Am I blacklisted or something. People used to help me out quite a bit more. Anyway, I discovered my problem. The exception was a red herring. The problem had nothing to do with my application resource definition. The problem I was having deep inside my resource dictionaries. I was merge-referencing a dictionary inside my dictionary that no longer existed. That was difficult to figure out.
Are these dictionaries in the same XAP? If so, a relative path should work. I have used all relative paths to merge in dictionaries without any issue. Here is an example of mine:
<Application.Resources>
<ResourceDictionary x:Name="appDictionary">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary x:Name="ControlStylesDictionary"
Source="Resources/Styles/ControlStyles.xaml" />
<ResourceDictionary x:Name="MenuStylesDictionary"
Source="Resources/Styles/MenuStyles.xaml" />
</ResourceDictionary>
</Application.Resources>
That is the only difference I can see in your XAML.
If the dictionary is in another XAP, you need to download the XAP and load the dictionary from there.
I ran into the same problem, same generic error message and found the solution. This appears to be a bug IMHO.
I am building an app for .Net, SL5, WP7.1. To do this I put the code in the .Net app and add source links for the other projects. Works great.
My main app projects are called MyApp.Net, MyApp.SL, and MyApp.WP. However, I make the default namespace and project output for these projects simply MyApp. Again, works great as it should.
I place my resources in projects MyApp.Resources.Net, MyApp.Resources.SL, and MyApp.Resources.WP. There is a bit of a glitch with using the VS source links as Expression Blend wants direct access to the physical files and gets confused when (for example) the MyApp.Resources.WP project contains a source link to a MyStyles.xaml file in the MyApp.Resources.Net projects. Therefore, all my resource projects actually contain physical files. This works fine also, I just have to synch the files manually. No problems so far.
However, for my resource projects I change the namespace and output files to MyApp.Resources. This keeps my application code simple also, regardless the platform it's built for, the namespace is the same.
Yes, I know this is a bit complicated but it allows me to build for 3 platforms (technically 5 if you include Blendability and UnitTesting) all with the same code base.
To continue, if I create a ResourceDictionary as such
<ResourceDictionary Source="/MyApp.Resources;component/Styles/TextStyles.xaml"/>
I get the Failed to assign to property 'System.Windows.ResourceDictionary.Source' etc...
In short, I discovered that if the assembly name contains a '.' this error shows up. For example if I change my project names to simply 'Resources' it works fine. Or if I leave my projects with their default build names of 'MyApp.Resources.WP' it also works fine.
This has nothing to do with changing my resource dll output file names, I change them all day long and it works great, but if they contain a '.' I get the above error. For example, I can change the output name to "MyAppResourceThatWorks" (leaving the project name as MyApp.Resources.WP and load it in App.xaml with
<ResourceDictionary Source="/MyAppResourceThatWorks;component/Styles/TextStyles.xaml"/>
Works great. Change the output name to "MyAppResourcesThatDoNot.Work" and load it with
<ResourceDictionary Source="/MyAppResourceThatDoNot.Work;component/Styles/TextStyles.xaml"/>
Fails.
Yes, I tried changing the assembly properties, etc. etc. It's a load issue with Pack Uri's.
In my WPF project i keep a user control in a separate library project. The user control accesses resources in a separate XAML file, like this:
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Resources/ViewResources.xaml" />
</ResourceDictionary.MergedDictionaries>
<!-- Local styles here -->
</ResourceDictionary>
</UserControl.Resources>
The resource file, ViewResources.xaml, resides in a folder in the control library project named Resources. It has the default build action (Page) and custom tool (MSBuild:Compile).
The problem is when I reference the control library in my WPF application and use the user control. At runtime, I get the following XamlParseException:
Set property 'System.Windows.ResourceDictionary.Source' threw an exception.
...which wraps the IOException:
Cannot locate resource 'resources/viewresources.xaml'.
How can I fix this? I have tried to change the resource file's build action to "content" and have it copied to the output directory (that works for files and similar "dumb" resources). But to no avail. Also, it doesn't work property in the user control then.
Is there a better way to specify the path?
Will I have to move the resource file to the application project (I'd rather not, as it belongs in the user control's domain).
Found it.
Turns out there is a better way to specify the path, Pack URIs. I changed the XAML to the following:
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/RoutingManager;component/Resources/ViewResources.xaml" />
</ResourceDictionary.MergedDictionaries>
<!-- Local styles here -->
</ResourceDictionary>
</UserControl.Resources>
and that fixed it.
I thought it was worth posting this just in case anyone else is struggling with the same problem, as I've spent over two hours fighting with syntax, etc. only to find that the solution was dead simple, but not that apparent:
When referencing a packed resource from another control library, it seems to work fine at design time, and even compiles without error, but fails at runtime with the 'Set property 'System.Windows.ResourceDictionary.Source' threw an exception' error. It turns out that simply referencing the resource assembly from your control library is not enough, you ALSO need to add a REFERENCE to the assembly containing the resource dictionary in you main application assembly, else it seems it does not get compiled into the application. (i.e. Startup Application (the one with app.xaml) -> Add Reference -> select assembly with referenced resource file/s).
Hope this helps!
In my case I had the ResourceDictionary and the UserControl on the same Library, but separate from the main application. What worked for me was specifying the name of the assembly in the format Adam suggested in the comment AND I had to change the ResourceDictionary in the project from Embedded Resource to Page. I didn't try using the pack:// format, but I assume it would work too.
<ResourceDictionary Source="/AssemblyName;component/Assets/MyResource.xaml"/>
I had the same error (IOException - file not found), which cost me a day of my life that I'll never get back.
Using neither the simpler "/assemblyname..." nor the "pack://...." syntax worked for me.
I was referencing the resource assembly in my main assembly correctly.
The error disappeared when I changed my xaml resource file Build Action property to "Resource", as mentioned above.
However, I then encountered a XamlParseException at this line:
<ImageBrush x:Key="WindowBackground" ImageSource="Images/gradient.png" />
(which I had hand-typed).
This left the xaml resource file I was trying to include with effectively an invalid dependency.
Oddly the fix was to delete the ImageSource property I had typed, re-insert it BUT select the image from the pulldown menus that appear as a result.
Even though the resulting line appears exactly the same, it clearly isn't.
Starting to dislike WPF (VS2013), but hope this helps.
:0/
I had the same situation, but the Pack URIs didn't help me, I was still getting "Cannot locate resource..." exception in the referencing (executable) project. What helped me, was the setting of my ResourceDictionary files in the custom control library project as Embedded Resource.
Whenever I try to reference the following namespace in my XAML, the code compiles and the project starts, but the InitializeComponent method throws an error. Here's the XAML reference:
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
and here's the use of ExtendedVisualStateManager
<ei:ExtendedVisualStateManager/>
The error is this:
The type 'ExtendedVisualStateManager' was not found because 'http://schemas.microsoft.com/expression/2010/interactions' is an unknown namespace. [Line: 19 Position: 37]
Is there a new namespace I need to use to use this control?
Here are some facts.
The Microsoft.Expression.Interactions.dll version 4.0.5.0 contains the namespace Microsoft.Expression.Interactivity.Core.
This Microsoft.Expression.Interactivity.Core contains the type ExtendedVisualStateManager.
The Microsoft.Expression.Interactions.dll version 4.0.5.0 carries a XmlnsDefinition that maps the URL "http://schemas.microsoft.com/expression/2010/interactions" to the namespace Microsoft.Expression.Interactivity.Core.
Hence a project referencing version 4.0.5.0 of Microsoft.Expression.Interactions.dll can contain Xaml using xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" that can then contain ei:ExtendedVisualStateManager.
You'll note I've repeated the version number a few times. If you do have an interactions dll referenced in a Silverlight 4 project but your code doesn't work then perhaps its the wrong version. However in that case Dan's answer should still have worked.
Make sure your Silverlight application has a reference to the Microsoft.Expression.Interactions assembly.
<UserControl
xmlns:ei="clr-namespace:Microsoft.Expression.Interactivity.Core;assembly=Microsoft.Expression.Interactions"
...other namespaces... />
<VisualStateManager.CustomVisualStateManager>
<ei:ExtendedVisualStateManager/>
</VisualStateManager.CustomVisualStateManager>
</UserControl>
I had everything correct per the other answers and like you, the problem still existed. It was failing at runtime on a usercontrol in my project (and that project did reference Microsoft.Expression.Interactions).
However, that usercontrol was being used on a form in another project. Once I added the reference to Microsoft.Expression.Interactions to the outer project, the runtime error was solved. I was not loading assemblies dynamically and so I'm not 100% certain why this was a problem.
I think you should look in your project's properties. Find the references (Microsoft.Expression.Interactions or/and other "Expression" assemblies you may use, and set the "Copy Local" property to TRUE and try it again.
None of the answers solved this puzzling problem to me.
Apparently I needed Microsoft Expression Blend SDK for Silverlight 4.
Installing it has solved the issue.