I have in a UserControl the Property ImageSource. How can I set the ImageSource in my code behind to a Image in my Resources directory?

I want to bind the Image Source to the property ImageSource.

<Image Source="{Binding Path=ImageSource}" />
有帮助吗?

解决方案

In order to create a BitmapImage (which is derived from ImageSource) from a resource file in code, you would do the following, provided that the file MyImage.jpg is in a folder named Images of your Visual Studio project, and that its Build Action is set to Resource:

var uri = new Uri("pack://application:,,,/Images/MyImage.jpg"); 
ImageSource = new BitmapImage(uri); // set the ImageSource property

See also this answer.


You could also directly use the image resource without binding:

<Image Source="/Images/MyImage.jpg" />
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top