WPF - ObservableCollection

时间:2017-04-26 09:59:32

标签: wpf observablecollection aforge

我的ObservableCollection中有一个CameraWindow我手动从我的USB网络摄像头捕获图像。这是我的收藏:

public ObservableCollection<BitmapImage> CameraWindowCapturedImages { get; } = new ObservableCollection<BitmapImage>();

这就是我捕捉图像的方式

void Cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
    try
    {
        System.Drawing.Image img = (Bitmap)eventArgs.Frame.Clone();
        MemoryStream ms = new MemoryStream();
        img.Save(ms, ImageFormat.Jpeg);
        ms.Seek(0, SeekOrigin.Begin);
        BitmapImage bi = new BitmapImage();
        bi.BeginInit();
        bi.StreamSource = ms;
        bi.EndInit();
        bi.Freeze();
        this.latestFrame = bi;
        Dispatcher.BeginInvoke(new ThreadStart(delegate
        {
            previewWindow.Source = bi;
        }));
    }
    catch (Exception ex)
    {
    }
}

private void manualCapture_Click(object sender, RoutedEventArgs e)
{
    if (captureImage != null)
    {
        captureImage(latestFrame);
    }
    Bitmap bm = BitmapImage2Bitmap(latestFrame);
    CapturedImages.Add(latestFrame);
}
private Bitmap BitmapImage2Bitmap(BitmapImage bitmapImage)
{
    using (MemoryStream outStream = new MemoryStream())
    {
        BitmapEncoder enc = new BmpBitmapEncoder();
        enc.Frames.Add(BitmapFrame.Create(bitmapImage));
        enc.Save(outStream);
        System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(outStream);

        return new Bitmap(bitmap);
    }
}

我的ObservableCollection

中也有MainWindow
public ObservableCollection<BitmapImage> MainWindowCapturedImages { get; } = new ObservableCollection<BitmapImage>();

我希望在CameraWindow MainWindow ObservableCollection的{​​{1}}中存储手动捕获的图片。

这是否可能,如果有可能有人请帮助我吗? 谢谢!

2 个答案:

答案 0 :(得分:1)

你需要以某种方式获得对窗口的引用。最简单的方法是使用Application.Current.Windows集合:

MainWindow mainWindow = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();
if(mainWindow != null)
{
    mainWindow.MainWindowCapturedImages.Add(latestFrame);
}

答案 1 :(得分:0)

快速执行此操作的方法是(C#6和WPF):

(App.Current.MainWindow as MainWindow)?.Items.Add(image);

我也不建议这样做。您应该使用MVVM模式,这是WPF应用程序的推荐开发技术