Kevin Babcock
Kevin Babcock

Reputation: 10247

How to bind to an Image using a dynamic URL in WPF?

I am new to WPF so hopefully I phrased the question correctly. What I'd like to do is bind my <Image> to an image online. However, the image I would like to bind to changes depending on the state of the application. For example, if I wanted to bind to an Employee selected from a list, I'd retrieve a base URL from my App.config and append the image name using the ID of the employee, like so:

var baseUrl = ConfigurationSettings.AppSettings["BaseImageUrl"];
var imageUrl = String.Format("{0}/{1}.jpg", baseUrl, employeeID);

The problem is, I'm not sure how to do this declaratively in WPF. Any help is greatly appreciated!

Upvotes: 5

Views: 14527

Answers (2)

Jake Ginnivan
Jake Ginnivan

Reputation: 2142

Do you have a employee object in your code? If so you could expose a URI property which is built based on the employee ID of the object.

Otherwise could you have a asp.net page on your website which serves up a image (I have no idea if this will work, it is a idea though)

so have something like this in your xaml

<Image Source="{Binding Path=EmployeeId, StringFormat='http://my.url.com/Image.aspx?employeeId={0}'}" />

Image.aspx would stream the image based on the employeeId get variable?

As I said there is probably a bit wrong with this but it could work, I think the URI property on a employee class would be the cleanest option though.

Upvotes: 3

Paul Stovell
Paul Stovell

Reputation: 32715

I think something like this will help:

<Window.Resources>
   <ImageSource x:Key="MyImage" Source="C:\Images\Default.jpg" />
</..>

<Image Source="{DynamicResource MyImage}" />

Then in your code-behind:

((ImageSource)this.Resources["MyImage"]).Source = "C:\Path\From\Config.jpg";

Upvotes: 0

Related Questions