1

我在从不同线程中显示弹出窗口时遇到问题。我已尝试阅读此处的其他一些问题,但我无法理解如何应用它们...

我有一个使用相机的应用程序,我想在可用后弹出图片的预览。

PhotoCamera 有“CaptureImageAvailable”事件,我想在其中弹出预览

private void cam_CaptureImageAvailable(object sender, ContentReadyEventArgs e)
    {
        BitmapImage img = new BitmapImage();
        img.SetSource(e.ImageStream);
        e.ImageStream.Close();

        //creating the new pop-up preview
        Grid panelPreview = new Grid();
        panelPreview.Background = new SolidColorBrush(Colors.Black);
        panelPreview.Width = 300;
        panelPreview.Height = 400;

        //create an ImageBrush to display the image in the new pop-up
        ImageBrush imgPreview = new ImageBrush();
        imgPreview.ImageSource = img;

        //need a rectangle to add the image to, otherwise can't add it
        Rectangle rect = new Rectangle();
        rect.Width = 300;
        rect.Height = 400;
        rect.Fill = imgPreview;

        //Adding the rectangle to the grid
        panelPreview.Children.Add(rect);

        imagePreview.IsOpen = true;

        ....
    }

这会导致 UnauthorizedAcessException,这对我来说很有意义,因为这个事件在不同的线程上,但我不明白如何修复它......我也尝试过使用这段代码

private void cam_CaptureImageAvailable(object sender, ContentReadyEventArgs e)
    {

        Deployment.Current.Dispatcher.BeginInvoke(delegate()
        {

            BitmapImage img = new BitmapImage();
            img.SetSource(e.ImageStream);
            e.ImageStream.Close();

            //creating the new pop-up preview
            Grid panelPreview = new Grid();
            panelPreview.Background = new SolidColorBrush(Colors.Black);
            panelPreview.Width = 300;
            panelPreview.Height = 400;

            //create an ImageBrush to display the image in the new pop-up
            ImageBrush imgPreview = new ImageBrush();
            imgPreview.ImageSource = img;

            //need a rectangle to add the image to, otherwise can't add it
            Rectangle rect = new Rectangle();
            rect.Width = 300;
            rect.Height = 400;
            rect.Fill = imgPreview;

            //Adding the rectangle to the grid
            panelPreview.Children.Add(rect);

            imagePreview.IsOpen = true;
        });

此方法不会引发任何错误,但似乎也没有实际执行任何操作。如何在 UI 线程上显示此弹出窗口?

4

2 回答 2

0

你可以使用 Dispatcher,像这样

Deployment.Current.Dispatcher.BeginInvoke(()=>{

      something...

});
于 2012-10-18T09:23:42.163 回答
0

什么是“图像预览”?
如果它是任何类型的弹出窗口或图像元素容器,则您必须添加“panelPreview”作为它的子元素,以便它在 UI 上可见。

还有一件事,你可以使用缩略图(通过

私有 void cam_CaptureThumbnailAvailable(对象发送者,ContentReadyEventArgs e)

) 用于在弹出窗口上查看,这将比实际图像占用更少的内存。

于 2012-10-18T12:29:27.690 回答