当事件处理程序完成时导航到一个页面?

时间:2012-10-17 13:29:39

标签: c# windows-phone-7 windows-phone-7.1 windows-phone windows-phone-7.1.1

所以我想在WP7中做一个非常简单的事情,如:

MainPage中的一个按钮将启动摄像头,当摄像头成功拍照时,我想将图片传递给SecondPage并启动它。

这是我的代码:

在MainPage构造函数中,我初始化摄像头任务并设置委托:

camTask.Completed += new EventHandler<PhotoResult>(camTask_Completed);

然后我实施了camTask_Completed

 void camTask_Completed(object sender, PhotoResult e)
    {
        //throw new NotImplementedException();

        img = PictureDecoder.DecodeJpeg(e.ChosenPhoto);
        NavigationService.Navigate(new Uri("/SecondPage.xaml", UriKind.Relative));
    }

在我拍完照片之后按下“接受”之后,应用程序将无错误地运行。

例外说:

Exception {"Navigation is not allowed when the task is not in the foreground."} System.Exception {System.InvalidOperationException}

我理解的是我不应该在camTask_Completed方法中启动SecondPage。

然后我的问题是:如何在EventHandler的结果上启动另一个页面?

由于

更新(有关此子问题的回答,请参阅此页面中的comment

单击按钮(启动相机)后,我发现了另一个错误:

它抛出异常说:

"Type 'System.Windows.Media.Transform' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute."

我可以在哪里序列化Transform内容?

我在Google上进行了一些搜索,找到了this

  

找到答案,错误实际上也表明了这一点:)

     

[DataContract]

     

[KnownType(typeof运算(System.Windows.Media.MatrixTransform))]

似乎它可以解决这个问题,但我应该把这些行放在哪里?

这是我在MainPage上将代码传递给SecondPage的代码,imgWriteableBitmap

 protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
    {
        base.OnNavigatedFrom(e);
        var brush = new ImageBrush();
        brush.ImageSource = img;
        PhoneApplicationService.Current.State["bkg"] = brush;
    }

再次感谢。

2 个答案:

答案 0 :(得分:1)

也许您应该尝试使用调度程序:

activePage.Dispatcher.BeginInvoke(
     () => NavigationService.Navigate(new Uri("/SecondPage.xaml", UriKind.Relative)));

这适用于MetroApps。

答案 1 :(得分:0)

这是CameraCaptureTask的一个已知问题 以下是我使用的解决方法:

    void OnCameraCaptureTaskCompleted(object sender, PhotoResult args)
    {
        //Delay navigation until the first navigated event
        NavigationService.Navigated += new NavigatedEventHandler(navigateCompleted);
    }

    void navigateCompleted(object sender, EventArgs e)
    {
        //Do the delayed navigation from the main page
        this.NavigationService.Navigate(new Uri("/Page1.xaml", UriKind.Relative));
        NavigationService.Navigated -= new NavigatedEventHandler(navigateCompleted);
    }