I've noticed that when I add a line of <Window.Background></Window.Background> in the XAML file or in the C# code this.Background = new ImageBrush(new BitmapImage(new uri([...])); if I put in the "Uri" this: new Uri(#"pack://application:,,,/Myapp;component/image.jpg") I get an error when I try to compile it which says: "Could not locate resource "image.jpg" "
But if I change this to new Uri(System.IO.Directory.GetCurrentDirectory()+"\\image.jpg"); it never gives me an error. Why???? What is the difference between both methods? I am very comfortable with Directory but why the compiler doesn't show an error "Locating" the resource with IO.Directory? What's the difference?
The questions may sound too noob, but I don't understand why it gives an error in #"pack://application[...] and not with GetCurrentDirectory()
A pack:// Uri, will search embedded resources for the image. The resources are inside the DLL/EXE, rather than deployed to the same folder. To use an image as a WPF Resource you need to set the Build Action on the image to Resource.
Using the Directory approach simply searches the physical file system for the image.
More info here on WPF Pack Uri's.
Related
I am using a custom cursor named hand2.cur in my C#-WPF application. I have added the cursor to a folder named Images which has all the images that I use in my application. However I've realized that I cannot add relative path to use my custom cursor as:
Cursor newCur = new Cursor("Images\\hand2.cur");
window.Cursor = newCur;
So I used this:
string absolute = System.IO.Path.GetFullPath("hand2.cur");
Cursor newCur = new Cursor(absolute);
window.Cursor = newCur;
This tries to find the hand2.cur file in the \bin\Release folder. So I added the file there and I got it working.
But the problem is, if I Publish this application and use it on a different computer, it does not work. Now the problem is with the cursor file path, because if I deploy it after commenting those 3 lines, it works correctly. So what do I do to rectify this problem?
I am using other images from the Image folder in my XAML code and they seem to port fine. But then again my knowledge of WPF is limited so if anyone has any ideas, that would help.
EDIT: I have added my Images folder to the project. I have also set the Build Action of the cursor file hand2.cur to Embedded Resource. However when I use the following two lines, I get an XAMLParseException.
System.Windows.Resources.StreamResourceInfo info = Application.GetResourceStream(new Uri("pack://application:,,,/Slideshow;component/Images/hand2.cur"));
window.Cursor = new System.Windows.Input.Cursor(info.Stream);
The Inner Exception field when I view the details of the error reads: {"Cannot locate resource 'images/hand2.cur'."}
You could make the cursor a resource in your app/assembly and then use GetResourceStream with the pack Uri to the resources location. Pass the Stream of the StreamResourceInfo to the ctor of the Cursor. e.g.
var info = Application.GetResourceStream(new Uri("pack://application:,,,/Images/hand2.cur"));
var cursor = new Cursor(info.Stream);
I've got this working after I added the cursor file hand2.cur to my Resource1.resx resource file. Then I used the following statement in my code:
window.Cursor = new Cursor(new System.IO.MemoryStream(MyNameSpace.Resource1.hand2));
I'm following one of the MSDN Introduction to Windows Phone Development labs, and have run into a problem with this lab (Introduction to Controls Available for Windows Phone Applications). The lab provides both the starting files, and the end files (i.e., what the program should look like upon completion of the lab).
The particular part of the lab that has me stumped is the point where I'm reading in a series of images from an Assets folder, then displaying them in a ListBox on screen. Whenever this code tries to run, it throws a Null Reference Exception:
public static BitmapImage GetImage(string filename)
{
string imgLocation = Application.Current.Resources["ImagesLocation"].ToString();
StreamResourceInfo imageResource = Application.GetResourceStream(new Uri(imgLocation + filename, UriKind.Relative));
BitmapImage image = new BitmapImage();
image.SetSource(imageResource.Stream);
return image;
}
I've dug into as much as I can, and imageResource always winds up Null somehow, and I can't for the life of me figure out where it's going wrong.
I've included a link to the two projects here (129 MB, sorry for that). Everything under the "Begin" folder is what I've done so far (and throws an Exception when I attempt to navigate to the Images page during runtime). Everything under the "End" folder is what it's supposed to end up looking like, and is functional.
I'm very new to C# and WP7 development, so any help would be greatly appreciated. Thank you!
Try to change the build for the .bmp to "Resource".
Here's a couple of links explaining it:
http://forums.silverlight.net/t/238891.aspx/1
Application.GetResourceStream called on a Content Resource still return null
The problem is that when you set your images directory in App.xaml file, there is a mistake in the tutorial. You should set the application resource, ImagesLocation like this:
<system:String x:Key="ImagesLocation">Begin;component/Assets/Images/</system:String>
Where Begin is your project name ;component/ is needed as separator, and finally the Assets/Images/ is the relative path to your images directory.
C# - Loading image from file resource in different assembly
I have a PNG image file which is stored in a project called SomeProject and displayed various times using XAML in that same project. In a different assembly, I now wish to access that same image. Previously I was simply specifying a relative path to the actual file which worked fine. However, when I build a release installer, the image files are packed into the SomeProject.DLL.
Is there any easy way I can access the PNG file from another assembly without simply resorting to copying the file locally to the second project? I though it might be possible using 'pack://' but I'm not having much luck.
// SomeOtherProject.SomeClass.cs ...
Image logo = new Image();
BitmapImage logoSource = new BitmapImage();
eChamSource.BeginInit();
// Following line works fine is Visual Studio, but obviously not after installation
// logoSource.UriSource = new Uri(#"..\SomeProject\Resources\Images\logo.png", UriKind.Relative);
logoSource.UriSource = new Uri("pack://application:,,,/SomeProject;component/Resources/Images/logo.png");
logoSource.EndInit();
logo.Width = 100; logo.Height = 100;
logo.Source = logoSource;
Any advice would be good.
If the images you wish to use as Content is in another assembly, you must copy them to the main projects directory.
You can use a Build event to do this:
Right click project that contains images -> Properties -> Buil Events -> edit post build to copy images to main project directory.
Then you have to use it as
pack://application:,,,/ContentFile.xaml
(Or)
If you need it in subfolder
pack://application:,,,/Subfolder/ContentFile.xaml
Have a look at this hfor more information http://msdn.microsoft.com/en-us/library/aa970069.aspx
Try to load your other assembly as followed:
Application.LoadComponent(new Uri(#"AnotherAssembly;;;component\AnotherResourceFilePath/logo.png", UriKind.Relative)));
LoadComponent function returns an object. It is up to you to cast it to the appropriate type.
I have a problem with displaying certain images in my application using C#. I am using the Image class to specify the location and the BitmapImage to specify the source. The UriSource is relative and I just specify the name. It worked for some images, but for others, the image simply does not appear. My image instance is 35x35 big and another is 100x100 big (pixels).
Anyone knows why this might be occurring and how to fix it?
Thanks.
Here's the code I used:
Image removeImage = new Image();
removeImage.HorizontalAlignment = HorizontalAlignment.Left;
removeImage.VerticalAlignment = VerticalAlignment.Top;
removeImage.Margin = new Thickness(490, 10, 0, 0);
removeImage.Width = 35;
removeImage.Height = 35;
BitmapImage source = new BitmapImage();
source.BeginInit();
source.UriSource = new Uri("delete.png", UriKind.RelativeOrAbsolute);
source.EndInit();
removeImage.Source = source;
removeImage.Stretch = Stretch.None;
removeImage.Visibility = Visibility.Visible;
removeImage.MouseDown += new MouseButtonEventHandler(removeImage_MouseDown);
Not sure about the location of image files. If images are in your current project folder then you have to set Copy To Output Directory=Copy Always property of image file from Properties Windows.
The best way that I know of to diagnose a problem like that (assuming a quick peer review of the code gets you nowhere), is to use ProcessMonitor: http://technet.microsoft.com/en-us/sysinternals/bb896645
You can use this tool to monitor all of the file activity on your machine (make sure to use the include/exclude filters to limit the noise).
It's very likely that the reason that the images are not showing up is because your application is looking for them in the wrong place (either they didn't get copied, or the relative path is off).
ProcessMonitor will log every attempt that Windows makes to access your .jpg (whether it fails or succeeds). If you search for your file name in the log, you should find it, probably along with an error message, and the full path that Windows was using to open the file.
The most common results I see are
Path that was actually being used was different from the path you needed.
The path was correct, but your files weren't there (build/copy/install problem)
The path was correct, but your web app did not have permissions to read the file.
In all those cases, ProcessMonitor will show you what happened.
I am trying to add a xaml resource file dynamically using the statement,
Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri("resources/leaf_styles.xaml", UriKind.Relative) });
This is throwing an exception, Cannot locate resource 'resources/leaf_styles.xaml'.
I added the leaf_styles.xaml file to the project under resource folder and the BuildAction is set to "Content", CopyAlways is set to True. Still I get this error. Could some one help me out pointing whats wrong??
Additional information -
I don't want to embed the xaml file as a resource
The current project is a .net 3.5 class library project
The above mergedictionary statement is written in a class belonging to the same project
I also added the [assembly: AssemblyAssociatedContentFile("resources/leaf_styles.xaml")] manually once I figured that this is not working (for testing)
Update
If I give it as an absolute location, it is working properly.
Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri(#"D:\foo\trunk\bin\resources\leaf_styles.xaml", UriKind.Absolute) });
At last, it worked. Here is what I did,
Went thru' http://msdn.microsoft.com/en-us/library/aa970069.aspx.
Changed the Uri pattern to
var foo = new Uri("pack://siteoforigin:,,,/resources/leaf_styles.xaml", UriKind.RelativeOrAbsolute);
Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = foo });
To load a content file, you can call the GetContentStream method of the Application class, passing a pack URI that identifies the desired content file.
Checkout
http://msdn.microsoft.com/en-us/library/aa970494.aspx#Content_Files
EDIT
I did it successfully like this
Uri uri = new Uri("Resources/MyDict.xaml", UriKind.Relative);
StreamResourceInfo info = Application.GetContentStream(uri);
System.Windows.Markup.XamlReader reader = new System.Windows.Markup.XamlReader();
ResourceDictionary myResourceDictionary =
(ResourceDictionary)reader.LoadAsync(info.Stream);
Application.Current.Resources.MergedDictionaries.Add(myResourceDictionary);
I encountered same "missing resource problem" and scratched my head for hours. Then I realized that my assembly name contains dots (.) and changed the resource assembly name, tested again and it worked. It was a 16x16 png image file which ı wanted to load. But I see that dotted assembly names causes error for soma cases and does not cause error for other cases.
1) If you are loading a style from resource, it works
2) If you are loading an image, it does not work. The resource can not be found.
I used the same code for both cases but results are different. I don't know if it is a wpf bug.