【问题标题】:WPF - ObservableCollectionWPF - ObservableCollection
【发布时间】:2017-04-26 09:59:31
【问题描述】:

我的CameraWindow 中有一个ObservableCollection,我在其中手动从我的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);
    }
}

我的MainWindow 中也有ObservableCollection

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

我想将手动捕获的图像存储在我的CameraWindow 中的MainWindowObservableCollection 中。

这可能吗?如果可以,请有人帮我解决这个问题? 谢谢!

【问题讨论】:

  • 您可以将一个可观察集合分配/复制到另一个。您在代码中的哪个位置分配/复制所需的集合?这样做的障碍是什么?
  • 您是在询问如何将 BitmapImage 对象添加到主窗口中的 MainWindowCapturedImages 集合中,或者您的问题是什么?
  • @mm8 询问如何将 BitmapImage 对象添加到我的主窗口中的 MainWindowCapturedImages 集合中
  • 从什么方法?
  • 我目前正在使用manualCapture_Click 中的Action&lt;BitmapImage&gt; captureImage; 将捕获的图像添加到我的CameraWindowCapturedImages

标签: wpf observablecollection aforge


【解决方案1】:

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

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

【讨论】:

  • 我在哪里添加这个? (很抱歉问了愚蠢的问题,我是 C#/wpf 的初学者)
  • 也许在 manualCapture_Click 中?或者您希望能够访问主窗口的任何位置。只有你知道你想做什么......
  • 如果您还有其他问题,请提出新问题。
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多