我在从不同线程中显示弹出窗口时遇到问题。我已尝试阅读此处的其他一些问题,但我无法理解如何应用它们...
我有一个使用相机的应用程序,我想在可用后弹出图片的预览。
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 线程上显示此弹出窗口?