简体   繁体   中英

Unhandled exception thrown by PhotoChooserTask

I've got this code and I'm using it to show a button which allows the user to choose an image from his library and use it as a background for my app.

So I create a PhotoChooserTask , set it to show the camera and bind it to a method that has to be executed when the task is completed. The button will start the task by showing the PhotoChooserTask . The action to do on complete is quite easy, I've just got to set a boolean value and update an image source.

PhotoChooserTask pct_edit = new PhotoChooserTask();
pct_edit.ShowCamera = true;
pct_edit.Completed += pct_edit_Completed;
Button changeImageButton = new Button { Content = "Change Image" };
changeImageButton.Tap += (s, e) =>
{
    pct_edit.Show();
};


void pct_edit_Completed(object sender, PhotoResult e)
    {
        if (e.TaskResult == TaskResult.OK)
        {
            bi.SetSource(e.ChosenPhoto);
            IsRebuildNeeded = true;
        }
    }

The problem is that it won't show the PhotoChooserTask but it will give me an exception, taking me to

private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
    {
        if (Debugger.IsAttached)
        {
            Debugger.Break();
        }
    }

in App.xaml.cs .

This looks weird as I've got another PhotoChooserTask in the same class and this one works fine.

What's wrong with it?

VisualStudio won't even tell me what's the exception and so there's no way to figure it out!

EDIT:

I just found out that the exception is thrown when I call

pct_edit.Show(); 

in the button's tap event.

You should be defining your chooser as a field in your class. It's a requirement that you have page scope for the PhotoChooser. You then subscribe to it in your constructor. This is stated on the MSDN here

class SomeClass
{
   readonly PhotoChooserTask pct_edit = new PhotoChooserTask();

   SomeClass()
   {
       pct_edit.ShowCamera = true;
       pct_edit .Completed += new EventHandler<PhotoResult>(pct_edit_Completed);
   }
}

You can use try to check what is the problem

changeImageButton.Tap += (s, e) =>
{
    try
    {
       PhotoChooserTask pct_edit = new PhotoChooserTask();
       pct_edit.ShowCamera = true;
       pct_edit.Completed += (s,e) =>
       {
           if (e.TaskResult == TaskResult.OK)
           {
              var bi = new BitmapImage() // maybe you didn't initialize bi?
              bi.SetSource(e.ChosenPhoto);
              IsRebuildNeeded = true;
           }
       }
       pct_edit.Show();
    }
    catch (Exception ex)
    {
       Message.Show(ex.Message);
    }
};

Put brakepoint on Message , then you can check everything inside ex .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM