“实时"更新 WPF 控件 [英] Updating WPF control in "real time"

查看:108
本文介绍了“实时"更新 WPF 控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个应用程序,它将显示相机看到的当前图像,它需要实时或接近更新显示的图像.从本质上讲,我有一台可以捕捉图像的相机,我需要每隔一秒捕捉一个图像并将该图像显示在屏幕上.目前,我的应用程序有一个 Image 控件,我正在从相机捕获一个 BitmapImage 并将其设置为 Image.Source.我的麻烦是让它不断更新.不幸的是,我没有处理这样的事情的经验,这种事情必须永远更新自己(或直到我正在编写的应用程序关闭),老实说,似乎几乎没有(我已经能够发现)关于在 WPF/C# 中做这样的事情的网站.我怀疑我必须生成一个线程来执行图像捕获,但老实说,这是我的问题的一部分——我很少有使用线程的经验,并且对所有这些是如何工作的有点困惑.非常感谢您提供的任何帮助.

I'm writing an application which will display the current image seen by a camera and it needs to update the shown image in real time, or close to it. Essentially, I have a camera with which I can capture images and I need to capture one every, say, 1 second and display that image to the screen. Currently, my application has an Image control and I'm capturing a BitmapImage from the camera and setting this as the Image.Source. My trouble is getting this to continuously update. Unfortunately, I have no experience dealing with something like this that has to update itself forever (or until the application I'm writing is closed) and honestly there seems to be very little to none (that I have been able to unearth) on the web about doing something like this in WPF/C#. I suspect I'll have to spawn a thread to perform the image capturing, but honestly, that's part of my issue--I have very little experience working with threads and am a bit confused on how all that works. Thanks so much for any help you can provide.

推荐答案

为了使数据绑定得到正确更新,您可以使用 INotifyPropertyChanged.只需添加对 System.ComponentModel 的引用:

To make the data binding get updated properly, you can use INotifyPropertyChanged. Just add a reference to System.ComponentModel:

using System.ComponentModel;

然后继承接口:

MyWindow : INotifyPropertyChanged

然后添加以下代码:

public event PropertyChangedEventHandler PropertyChanged;

private void NotifyPropertyChanged(String info)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(info));
    }
}

最后,添加您要绑定到的属性.

Finally, add your property that you want to bind to.

private BitmapImage currentImage;
public BitmapImage CurrentImage{get{return currentImage;} set{currentImage=value;NotifyPropertyChanged("CurrentImage");}}

最后,在您的 xaml 中,将绑定更改为 {Binding CurrentImage},然后对于窗口,将数据上下文设置为相对源自身...这将是窗口的属性:

Finally, in your xaml, change the binding to {Binding CurrentImage} and then for the window, set the data context to relative source self... this would be a property for the window:

DataContext="{Binding RelativeSource={RelativeSource Self}}"

这应该能让绑定正常工作.在单独的线程上做事需要调度员

That should get the binding working properly. Doing things on a separate thread would require the dispatcher

这篇关于“实时"更新 WPF 控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆