Unhandled exception thrown by PhotoChooserTask

那年仲夏 提交于 2020-01-03 17:10:24

问题


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.


回答1:


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);
   }
}



回答2:


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.



来源:https://stackoverflow.com/questions/18105301/unhandled-exception-thrown-by-photochoosertask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!