Click here to Skip to main content
15,887,910 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have an image called Cameleon.png sitting in Assert Folder.
int my MainPage_Loaded function I write something like this

C#
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
     Task<writeablebitmap> imtask = GetImage();
     imtask.ContinueWith(t =>
     {
            WriteableBitmap writeableBmp = t.Result;
            ImageName.Source = writeableBmp;
     });
}

async Task<writeablebitmap> GetImage()
{
     string strImageName = string.Format("ms-appx:///Assets/Cameleon.png");
     Uri uri = new Uri(strImageName);

     WriteableBitmap bitMap = await new WriteableBitmap(1, 1).FromContent(uri);
        //    ImageName.Source = bitMap;
     return bitMap;
}

in my XAML file
XML
<Canvas>
 Image Canvas.Left="0" Canvas.Top="0" x:Name="ImageName"
</Canvas>

If I set ImageName.Source = bitMap; in my Task function it show the image, but if set in my MainPage_Loaded function it does NOT show.

What I am doing wrong?

Your help will be very much appriciated.

Best regards
Agha Khan
Posted
Updated 27-Mar-13 15:06pm
v2
Comments
Sergey Alexandrovich Kryukov 27-Mar-13 18:47pm    
Please tag it: WPF.
—SA
AghaKhan 27-Mar-13 19:49pm    
Update:
It looks like I can't add anything to my canvas.

I added this code in callback function as well as in my main function.
Rectangle r2 = new Rectangle();
r2.Height = 100;
r2.Width = 100;
r2.Fill = new SolidColorBrush(Colors.Red);

MyCanvas.Children.Add(r2);

I am unable to add any object to my canvas in my callback funtion. :-(
[no name] 27-Mar-13 20:35pm    
It might be that GetImage is async but you are not waiting for the task to complete. Try using await and see if that helps.
AghaKhan 27-Mar-13 21:35pm    
I NOT have to wait because ContinueWith means the Task is compleated. I posted the solution. It works now.
Prasad Khandekar 27-Mar-13 21:26pm    
Hello AghaKhan,

Why not try it MSDN way.
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
Task<writeablebitmap> imtask = GetImage();
WriteableBitmap writeableBmp = await imtask;
ImageName.Source = writeableBmp;
}

1 solution

This is very unusual behavior, but there is a solution. There is need an extra parameter for ContinueWith call.
imtask.ContinueWith(t =>
{

if (t.IsFaulted == false)
{
WriteableBitmap writeableBmp = t.Result;
myImage.Source = writeableBmp;
}
}, TaskScheduler.FromCurrentSynchronizationContext());

Now it works fine.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900