Unable to set image source in code

There are many questions and answers regarding setting an image source in code, for example, Setting up a WPF image source in code.

I followed all these steps and still could not set the image. I am code in WPF C # in VS2010. I have all my image files in a folder named " Images ", and all image files are set to Copy Always . And the assembly action is set to Resource , as indicated in the documentation.

My code is as follows. I installed dog.png in XAML and changed it to cat.png in the code.

// my XAML <Image x:Name="imgAnimal" Source="Images/dog.png" /> // my C# BitmapImage img = new BitmapImage(); img.UriSource = new Uri(@"pack://application:,,,/FooApplication;component/Images/cat.png"); imgAnimal.Source = img; 

Then I get an empty empty image of emptiness. I don’t understand why .NET makes it easy to configure .w image

[EDIT]

So the following work

 imgAnimal.Source = new BitmapImage(new Uri(@"pack://application:,,,/FooApplication;component/Images/cat.png")); 

This works, but I do not see the difference between the two codes. Why doesn’t it work before, but does the latter? For me they are the same ..

+4
source share
1 answer

Try the following:

 imgAnimal.Source = new BitmapImage(new Uri("/FooApplication;component/Images/cat.png", UriKind.Relative)); 

UriKind is Absolute by default, you should use the Relative one.

[EDIT]

Use BeginInit and EndInit:

 BitmapImage img = new BitmapImage(); img.BeginInit(); img.UriSource = new Uri(@"pack://application:,,,/FooApplication;component/Images/cat.png"); img.EndInit(); imgAnimal.Source = img; 
+11
source

Source: https://habr.com/ru/post/1401762/


All Articles