【问题标题】:Examples of collection changed events on Observable CollectionObservable Collection 上的集合更改事件示例
【发布时间】:2023-03-15 19:21:01
【问题描述】:

我在 WPF 应用程序中有一个列表框,它显示照片对象的可观察集合。当照片被添加到集合中时,UI 需要立即显示新图像。我知道这可以使用 CollectionChanged 事件来处理。我四处寻找有关如何使用句柄集合更改事件的示例,但我没有找到任何有效的方法。有谁知道有什么好的例子吗?

另一件事是图像来自我计算机上的一个目录,我有一个文件系统观察程序监视该目录是否有添加或删除的新照片。我目前正在使用文件系统事件处理程序在添加或删除照片时更新集合,但问题是当我将新照片添加到目录时,抛出异常说我无法从不是线程的线程修改集合主线程。有谁也知道如何解决这个问题?下面是这个问题的代码:

public class PhotoList : ObservableCollection<Photo>
{
    DirectoryInfo _directory;
    private FileSystemWatcher _watcher;

    public PhotoList()
    {
        _watcher = new FileSystemWatcher();
        MessageBox.Show("Watching..");
        _watcher.Filter = "*.jpg";
        _watcher.Path = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
        _watcher.EnableRaisingEvents = true;

        _watcher.Created += new FileSystemEventHandler(FileSystemWatcher_Created);

        _directory = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures));
    }

    public void Update()
    {
        foreach(FileInfo f in _directory.GetFiles("*.jpg"))
        {
            Add(new Photo(f.FullName));
        }
    }


    public string Path
    {
        set
        {
            _directory = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures));
            Update();
        }
        get
        {
            return _directory.FullName;
        }
    }

    public void FileSystemWatcher_Created(object sender, FileSystemEventArgs e)
    {
        Add(new Photo(e.FullPath));
    }
}

【问题讨论】:

    标签: c# wpf observablecollection inotifycollectionchanged


    【解决方案1】:

    将 Add(new Photo(e.FullPath)) 包装在 Dispatcher.Invoke() 中。这样,将在 UI 线程上调用 Add

    【讨论】:

      【解决方案2】:

      第一个问题:ObservableCollection&lt;T&gt; 已经实现了INotifyCollectionChanged,所以只需绑定该对象就可以了,UI 会自动获取集合中发生的更新。

      第二个问题:请参阅此帖子:WPF threading: can I update a control's data context in a non-UI thread? 和随附的 cmets。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-09
        • 1970-01-01
        • 1970-01-01
        • 2015-01-11
        相关资源
        最近更新 更多