Reputation: 71
I have a problem with updating an image source while the code is running.
I have a xaml page with the an image called ImagePack0
I have created at beginning of the xaml.cs class a method of a static class to put the image's into static variables so i can call them from everywhere.
//Put the image's in to static value's
StaticClass.PutImageintoStatic(ImagePack0);
After that the code makes certain calculations. Then when it knows what image should be stored in the image location it calls this static method.:
public static void PutImageIntoSource()
{
StaticClass.ImagePack0.Source = new BitmapImage(new Uri("\\Randomlocation\\RandomPicture.png", UriKind.Relative));
}
I call this static method and after this is executed i continue with other calculations. Now This code works. The only problem is that the xaml receives the update when my code stopped running. So how do i make the image source update instantly?
Anybody got any idea's?
Thanks in advance,
Upvotes: 1
Views: 904
Reputation: 149518
Your XAML receives the update only when your code finishes running because you are occupying the UI thread with work (in your case some calculations) which wont let your XAML update properly.
You need to offload work to a background thread, and update your UI when you're ready to add the image.
Assuming you're using .NET 4.5, ill use the Task
library:
public void SomeMethodWithCalculation()
{
// offload work to background thread, and update the UI when done.
Task.Run(() => StaticClass.PutImageintoStatic(ImagePack0)).ContinueWith(task => PutImageIntoSource, TaskScheduler.FromCurrentSynchronizationContex())
}
Assuming you are invoking work from the UI Thread, TaskScheduler.FromCurrentSynchronizationContext
will execute the continuation on that UI thread.
Upvotes: 2