Today I ran into a very odd issue when trying to reload the Silverlight Image Control with a new image which happened to have the EXACT same URL as the previously loaded image.
See in our application we provide a way to upload an image and also allow the user to not simply create a new image but rather swap out an existing image with a new one but leave the URL the exact same. During my development I really did not pay attention to or care that when I swapped out the image instance and raised the property changed event that the actual image was changing from the old to the new.
When I noticed that this was not working as expected I assumed that I could kill the instance of the object which was being bound to the <Image /> control in Silverlight and reset it w/ the new instance and that would trigger the reloading of the image via its url, however as you may have guessed this did not work. I had setup the binding to the control as follows:
Source="{Binding CurrentImage.SourceUrl}
I liked the binding code above (loading via URL rather than binary data) because I could easily hook into the loaded/failed events of the control in order to indicate to the user that there was something wrong with the image they are using.
It turns out (based on observations and Fiddler traces) that the Silverlight Image control will cache the current image and will NOT refresh/reload the image if the URL does not change. I guess the assumption is that if the same URL is provided multiple times don’t to waste cycles reloading it to only show the same image which is in memory.
This behavior works great in most cases…well until you don’t want it to work like this. I thought of a few ways to get around this issue, such as binding to a BitmapImage or binding to a byte[] array. However I really wanted to reduce the amount of rework or modifications I needed to make to the existing VM.
The solution we found that solved the issue was to bind to a image source url in the VM directly (did not want to dirty the existing SourceUrl Property as others user it and this work around is PURELY as UI issue, not a domain one) to a Url property in the VM and append an arbitrary query string value to the end of the URL.
public string CurrentImageSourceUrl
{
get
{
if (CurrentImage != null)
{
return string.Format("{0}?id={1}", CurrentImage.SourceUrl, Guid.NewGuid().ToString());
}
return string.Empty;
}
}
When I added the querystring value as above I was able to leave my existing VM logic alone and have the Image control reload the image correctly because it assumed that since my URL has changed that the images are different. I know this is a bit of a hack but hey it worked
. If anyone knows of a better way to solve this please let me know.
Till next time,
Posted
09-23-2011 12:24 PM
by
Derik Whittaker