I have a user control UserControl which is in an assembly Assembly. I have a WPF application which instantiates UserControl in a programmatic way. I have already added a reference to Assembly. However, during runtime I get the ff. exception:
Cannot locate resource 'usercontrol.xaml'.
at MS.Internal.AppModel.ResourcePart.GetStreamCore(FileMode mode, FileAccess access)
at System.IO.Packaging.PackagePart.GetStream(FileMode mode, FileAccess access)
at System.IO.Packaging.PackagePart.GetStream()
at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
...
I changed the build action for UserControl.xaml to EmbeddedResource but this caused compilation problems so I put it back to the default Page setting. I have tried this in .NET 3 and 4 to no avail. Anyone have any idea?
The most common cause of this is if you rename an assembly. I'll explain that scenario, then give some other possibilities.
Assume you have a DLL project "Abc" containing UserControl "MyControl". The generated InitializeComponent for MyControl in Abc.dll will contain the Uri "/Abc;Component/MyControl.xaml".
At runtime, the assembly name "Abc" is extracted and the loaded assemblies are searched for an assembly by that name. If such an assembly is found but it does not have a "MyControl.xaml" resource, you get the error you posted in the question.
So here is the scenario:
Now when you instantiate MyControl from Def.dll, it looks for its xaml in the Abc.dll assembly instead of the Def.dll assembly.
Some other scenarios in which this can happen:
You have a stale .g.cs file in your obj directory that has the wrong name for the xaml file. This can happen if you changed the source code without updating the date (which can happen during a checkout from a source control system or an unzip of a zip file or many other ways). Cleaning and rebuilding the solution will fix this. Since your comment says you tried this, this does not apply to you.
You are manually editing resource names in the .dll file after it has been compiled
You have loaded two assemblies with the same name (yes, this is possible), and the resource loader found the wrong one
Note that any change to the path to the XAML file, such as renaming or moving it, can cause this problem if the .g.cs file doesn't match the path in the resources.
To diagnose your problem further I recommend you download a copy of NET Reflector and look at your .dll file to see:
You can also examine the call stack at the point where the exception is thrown to make sure the resource manager being used has a reference to the expected assembly, not some other assembly.
I got this error after moving all my WPF windows to a new folder in the Project called "Windows". I corrected the error by going to "App.Xaml" and updating the Main window path to:
StartupUri="Windows\MainWindow.xaml"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With